Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will TCPStream.Read block until ALL data is received in send message?

I've written a multi-threaded simple server that uses:

clientStream.Read(message, 0, 4096);

To block until the client has sent a message. The code then goes on to process that message.

So far I've only been using it to send short commands

ex. "#login[username][login]"

but I'm worried that when I send huge table data over the line the code may continue before it has all been received.

So will .Read block until the whole sent message is received, or does it unblock when any data has begun receiving?

like image 725
Adrian Seeley Avatar asked Jun 12 '11 13:06

Adrian Seeley


1 Answers

Relying on a Send to finish to delineate between messages is bad form. If not for the simplest of reasons. I can telnet into your server and easily crash it.

You'll need to create a wire protocol. You have a few options.

  • Always expect the size of the message as a Unsigned 32-bit integer as the first 4-bytes, then read until you've filled that amount of data.

  • Specify a End of Message delimiter. This means you will maintain a buffer. You fill it with data off the wire, quickly scan it for end of message. Once you find a message you throw it to a message processor, then continue on with the left over bytes in the buffer, repeating step 1.

You can look at STOMP for an easy text based protocol.

Don't rely on your packets being sent in nice well-defined chunks as the message delimiter.

like image 95
Andrew T Finnell Avatar answered Nov 15 '22 11:11

Andrew T Finnell