Question

I want to send a file from a Linux server to a Windows client through sockets, the problem is that I receive more bytes than I send.

Server code----------------------------------------------

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();

Client code-----------------------------------------

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); 
}

Thanks,

Was it helpful?

Solution

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

One of your issues is that you always send 1024 bytes of the buffer even if you fread fewer bytes. (Note that 1348656 rounded up to the nearest multiple of 1024 is 1349632.)

So, on the write side you want something like:

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

and on the read side you want something like:

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

Your initial send is also problematic as you always send 1024 bytes with no check that this is the actual length of what is returned by c_str.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top