i need to send multiple messages on a TCP sockect connection using C# is it possible? if so, how to do it?
1 Answers
A TCP socket is just a stream; you simply keep writing to it. I suspect the problem here is how to break such a stream into discreet messages - for that you need to add some kind of logical framing into your stream. Obviously, the one thing you cannot do is "read until you get to the end of the stream", as that doesn't apply if sending multiple messages down the same socket.
For text-based messages this often means "write each message followed by a newline as a separator" (and "read until you get a newline"). For binary, it almost always takes the form of a length-prefix in some way. For example, a simple protocol might include 4 bytes before each message as the little-endian 32-bit integer representation of the length of the following message, so when writing it is "write the length, write the payload" - and when reading it is "read the length, read that many bytes, process that message" (note: 4 bytes is not necessarily a good way to do this, as it can't handle very large payloads - whether this is a problem depends on the data you want to send).
In both cases, because network packets are largely unrelated to how many times you call Write
/ Send
, your reading code will need to buffer and loop.
See also http://marcgravell.blogspot.com/2013/02/how-many-ways-can-you-mess-up-io.html which has more thoughts on this topic.

- 11,888
- 3
- 47
- 79

- 1,026,079
- 266
- 2,566
- 2,900