c++ - 接收比发送的 C++ 更多的字节

标签 c++ sockets send shutdown recv

我想通过套接字将文件从 Linux 服务器发送到 Windows 客户端,问题是我收到的字节数比发送的多。

服务器代码-------------------------------------------- -

if (resultEnviarLongitud = send(ClientSocket,GotFileSize.c_str(),1024,0)<0){
    cout<<endl<<"Error mandando la longitud! "<<endl;
}
rewind(fs);

while ((len = fread(Buffer,1,1024, fs)) > 0)
{
    if((resultEnviar = send(ClientSocket,Buffer,1024,0)) < 0){
        printf("ERROR: Failed to send file %s.\n", nombreArchivoADescargar.c_str());
        break;
    }
    sumEnviada+=len;
}

send(ClientSocket,"Hi",sizeof(Buffer),0);


cout<<"Bytes enviados: "<<sumEnviada<<endl;
strcpy(data, "");

cout<<endl<<"ARCHIVO MANDADO EXITOSAMENTE!"<<endl;
rutaArchivoADescargar.clear();

客户端代码----------------------------------------

if (resultRecibirLongitud = recv(sock, Buffer, sizeof(Buffer), 0) > 0)
{
    LongitudArchivo = atoi(Buffer);
    cout<<endl<<"Longitud Archivo a Recibir: " <<LongitudArchivo<<endl; 
}

FILE *fp=fopen("imagen.jpg","wb");
if (fp==NULL){
    cout<<"Error al crear archivo."<<endl;
}else{
    bzero(Buffer2, 1024); 
    int fr_block_sz = 0;
    int contador=0;

    //shutdown(sock, SD_SEND); I HAVE TO USE IT?

    while((fr_block_sz = recv(sock, Buffer2, 1024, 0)) >= 0) 
    {
        if (fr_block_sz == 0) break;
        if ( strcmp (Buffer,"Hi") == 0) break;
        int write_sz = fwrite(Buffer2, 1, 1024, fp);
        if(write_sz < fr_block_sz)
        {
            printf("File write failed on server.\n");
        }
        bzero(Buffer2, 1024);
        contador+=fr_block_sz;
        if (contador >= LongitudArchivo)break;
        bzero(Buffer2, 1024); 
    }
    cout<<endl<<"Numero de bytes recibidos: "<<contador<<endl<<endl;
    if(fr_block_sz < 0)
    {
        printf("Error receiving file from client to server.\n");
    }
    printf("Ok received from client!\n");
    fclose(fp); 
}

谢谢,

最佳答案

while ((len = fread(Buffer,1,1024, fs)) > 0)
{
    if((resultEnviar = send(ClientSocket,Buffer,1024,0)) < 0)

您的一个问题是您总是发送 1024 字节的缓冲区,即使您害怕更少的字节也是如此。 (请注意,1348656 四舍五入到最接近的 1024 的倍数是 1349632。)

因此,在写入方面,您需要这样的东西:

while ((len = fread(Buffer,1,1024, fs)) > 0)
{
    if((resultEnviar = send(ClientSocket,Buffer,len,0)) < 0)

在阅读方面你想要这样的东西:

while((fr_block_sz = recv(sock, Buffer2, 1024, 0)) >= 0) 
{
    // ...
    int write_sz = fwrite(Buffer2, 1, fr_block_sz, fp);

您的初始 send 也是有问题的,因为您总是发送 1024 字节而不检查这是 c_str 返回的实际长度。

关于c++ - 接收比发送的 C++ 更多的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19875364/

相关文章:

c++ - opencv mat与CImage之间的转换

c# - 从 C# 中通过引用传递,通过 C.L.I.到非托管 C++

java - Java中的 key SSL套接字连接

C文件服务器和客户端卡在recv上

sockets - socket通信中send()和recv()的行为

javascript - 如何将 chrome 扩展背景数据转为 javascript 函数

php - 为什么我用PHP插入数据库后不能使用数据

c++ - Cmake 和 QT5 - Include 只接受一个参数

c++ - 获取 C++ MFC 应用程序中的 CPU 数量

c++ - 我如何使用 ioctl() 在 VxWorks 的套接字上设置 FIONBIO?