File transfer through sockets, final size with less bytes

前端 未结 1 1011
天命终不由人
天命终不由人 2021-01-05 15:36

I\'m trying to receive some file through sockets in C. But the server sends me 64-byte packets for a 1000000 byte file for example and I get approximately 999902 bytes on th

1条回答
  •  有刺的猬
    2021-01-05 15:55

    The sending code provided ignores the fact that write() (or send() ) on a socket is not obliged to write the whole buffer.

    write()/send() might decide to write it partially or not write at all if the underlying subsystem refuses to receive more data (for example the network subsystem may have a queue for the data to send and this queue is already full). That's highly likely on a slow connection.

    The sending side should check the return value of write() to detect how much data has been actually written and adjust accordingly.

    Write should be done somehow like this:

    int readAmount;
    while( readAmount = read(file_fd, buffer, BUFSIZE) > 0 )
    {
        int totalWritten = 0;
        do {
           int actualWritten;
           actualWritten = write (sdaccept, buffer + totalWritten, readAmount - totalWritten);
           if( actualWritten == - 1 ) {
               //some error occured - quit;
           }
           totalWritten += actualWritten;
        } while( totalWritten < readAmount );
    }
    

    0 讨论(0)
提交回复
热议问题