Broken TCP messages

前端 未结 3 1774

I have a simple TCP server that communicates with some devices via GPRS. It works correctly without any problem for a long time. Nowdays there is a change in the devices (cl

3条回答
  •  庸人自扰
    2020-11-30 16:24

    The is no such thing as packets in TCP. It is a stream oriented protocol. That means when you read the socket you can get less data than you're expecting. You need to check the read size and if you got a short read then read again for 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;
    }
    

提交回复
热议问题