Read from socket: Is it guaranteed to at least get x bytes?

前端 未结 8 1922
一生所求
一生所求 2021-01-18 18:41

I have a rare bug that seems to occur reading a socket.

It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than th

8条回答
  •  滥情空心
    2021-01-18 19:39

    I assume you're using TCP. TCP is a stream based protocol with no idea of packets or message boundaries.

    This means when you do a read you may get less bytes than you request. If your data is 128k for example you may only get 24k on your first read requiring you to read again to get the rest of the data.

    For an example in C:

    int read_data(int sock, int size, unsigned char *buf) {
       int bytes_read = 0, len = 0;
       while (bytes_read < size && 
             ((len = recv(sock, buf + bytes_read,size-bytes_read, 0)) > 0)) {
           bytes_read += len;
       }
       if (len == 0 || len < 0) doerror();
       return bytes_read;
    }
    

提交回复
热议问题