You do not need to know anything. TCP is a stream protocol, and at any time you can get just one byte, or as much as a few megabytes of data. The correct and only way to use a TCP socket is to read in a loop.
char buf[4096]; // or whatever std::deque<char> data; for (int res ; ; ) { res = recv(fd, buf, sizeof buf, MSG_DONTWAIT); if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; // done reading } else { // error, break, die } } if (res == 0) { // socket closed, finalise, break } else { data.insert(data.end(), buf, buf + res); } }
The only purpose of the loop is to transfer data from the socket buffer to your application. Then your application must decide for itself whether there is enough data in the queue to try to extract some message from the application of a higher level.
For example, in your case, you would check if the queue size is at least 5, then check the first five bytes, and then check if the queue contains the complete application message. If not, you interrupt, and if so, you retrieve the entire message and drop out if it is turned off from the front of the queue.
source share