TCP fragmentation
I know that TCP provides stream-like data transmission, but the main question is - what situations can occur while sending data over TCP?
1. The message can be split to N chunks to fit in MTU size. 2. Two messages can be read in 1 recv call.Can there be the next situation?
MTU for example 1500 bytes. Client calls send with 1498 bytes data. Client calls send with 100 bytes data. S开发者_运维知识库erver calls recv and receives 1500 bytes data. Server calls recv and receives 98 bytes data.So it end up with situation when 2 bytes from second client send will be received in first server recv.
My protocol defined as foolows:
4 bytes - data length data content.I wonder can I came up with situation when 4 bytes (data length) will be split into 2 chunks?
Yes, a stream of bytes may be split on any byte boundary. You certainly can have your 4 byte data length header split in any of 8 different ways:
4
1-3
2-2
3-1
1-1-2
1-2-1
2-1-1
1-1-1-1
Some of these are more likely to occur than others, but you must account for them. Code that could handle this might look something like the following:
unsigned char buf[4];
size_t len = 0;
while (len < sizeof(buf)) {
ssize_t n = recv(s, buf+len, sizeof(buf)-len, 0);
if (n < 0) {
// error handling here
}
len += n;
}
length = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);
I always write my applications in a manner that expects the data to become fragmented somehow. It's not hard to do once you come up with a good design.
What's the best way to monitor a socket for new data and then process that data?
精彩评论