3

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.
Server 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?

2
  • Even if it does split it, does it make any difference. After all your data will be correctly relayed over to your destination, guaranteed by TCP. en.wikipedia.org/wiki/Transmission_Control_Protocol
    – DumbCoder
    Dec 29, 2010 at 9:32
  • There is no such thing as a "message" as far as TCP is concerned. If you have some concept of a message in your code, TCP knows nothing whatsoever about it. Sep 17, 2011 at 16:19

2 Answers 2

8

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);
2
  • 2
    The important thing is that this doesn't matter if you block and wait for the complete four bytes before proceeding. TCP will do its job and reassemble the fragmented data transparently.
    – cdhowie
    Dec 29, 2010 at 9:29
  • @cdhowie - While that may be true there is no guarantee that all the software standing between the code and the wire will construct packets in a 1-to-1 fashion with each SendData call. That is to say if somewhere down the line the byte array passed into the call is deemed too large for the circumstances there is nothing guaranteeing the message won't be split into multiple packets. Dec 29, 2010 at 9:45
1

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.