TCP messages arrival on the same socket

619 views Asked by At

I've got a 2 services that communicate using a TCP socket (the one that initiates the connection is a C++ Windows service and the receiver is a C# TCP stream) and (let's say that they might not use the same TCP connection all the time). Some of the time I'm getting half messages (where the number of bytes is miscalculated somehow) on a great network load.

I have several questions in order to resolve the issue:

  • Can I be sure that messages (not packets...) must follow one another, for example, if I send message 1 (that was received as half), then message 2, can I be sure that the next half of message 1 won't be after message 2? Please have separate answer for the same TCP connection between all messages and not having the same TCP connection between them.

  • Is there any difference whether the sender and the receiver are on the same station?

2

There are 2 answers

0
Dale Wilson On BEST ANSWER

TCP is a stream protocol that delivers a stream of bytes. It does not know (or care) about your message boundaries.

To send the data, TCP breaks the stream up into arbitrarily sized packets. [it's not really arbitrary and it is really complicated.] and send these reliably to the other end.

When you read data from a TCP socket, you get whatever data 1) has arrived, and 2) will fit in the buffer you have provided.

On the receive side you need to use code to reassemble complete messages from the TCP stream. You may have to write this yourself or you may find that it is already written for you by whatever library (if any) you are using to interact with the socket.

0
Some programmer dude On

TCP is a streaming protocol, it doesn't have "messages" or "packets" or other boundaries. Sometimes when you receive data you might not get all that was sent, other times you could get more than one "message" in the received stream.

You have to model your protocol to handle these things, for example by including special message terminators or including a fixed-sized header including the data size.

If you don't get all of a message at once, then you have to receive again, maybe even multiple times, to get all the data that was sent.

And to answer your question, you can be sure that the stream is received in the order it was sent, or the TCP layer will give you an error. If byte A was sent before byte B then it's guaranteed that they will arrive in that order. There is also no theoretical difference if the sender and receiver is on the same system, or on different continents.