Search code examples
c#c++tcpsocket

TCP messages arrival on the same socket


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?


Solution

  • 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.