tags:

views:

35

answers:

1

If a client sends multiple messages to a server over the same socket, will the EndReceive on the server side keep the messages seperated, or is it possible for the the server to receive partial messages from two seperate sends in a single BeginReceive?

+1  A: 

Assuming TCP, there're no message boundaries on the socket. One send might be consumed by multiple receives and the other way around, and partially. Treat TCP socket as a stream. Either send fixed-size messages so you know how many bytes to read, or embed message size into the message itself (preferably at the very beginning of the message) so you can find out as you go.

Edit:

To answer the questions in your comment - it's not only the "MS OS" that's doing this - it's TCP/IP stacks on both sides of the connection. The bytes written to a socket are buffered inside the kernel and sent on the wire when network stack thinks it's the best time to do so (in-kernel timeout is up, output queue reached TCP window size, etc. - it's all in the details of how TCP works). For TCP (but not for UDP) kernel does not keep track of application write boundaries, only of how many bytes are there to send, how many have been ack-ed, etc. It's a stream, the OS does not know about application messages, only bytes.

Nikolai N Fetissov
Is this really true? I am worried about this, but for this to happen, the MS OS layer would have to recieve a partial/whole message from one send, strip the header, receive a partial/whole message from a different send, strip the header and combine the two packets of data into a single message and forward it to BeginReceive. This can really happen?
Jess
Thanks a lot.. I was just about to edit my question to include that possibly the client side could also be buffering Sends before sending them. I have just tested this and indeed it is happening - I just blocked the server (breakpoint) and let multiple small messages build up from the client. While this isn't the answer I was hoping for, thank-you! :-)
Jess