Search code examples
c#socketsnetwork-programmingnetworkstream

NetworkStream.Read does not receive empty message


I'm trying to set up a TCP server, which reads incoming messages with NetworkStream.Read().

All is working well until an empty message is send - there is no reaction, as if nothing happened. Why is that? And what can I do to fix it?


Solution

  • TCP is a stream protocol, not a message protocol. Writing zero bytes to a stream: does nothing. As such, when sending messages on a stream you need a "framing" mechanism. This can be as simple as writing a length-prefix before each message, for example "the length as 4 bytes, 32-bit little endian", or "the length as readable ASCII decimal integer, followed by a line-feed character". So for the first, to write a zero-length message you'd write 4 bytes, 00 00 00 00 (4 bytes of prefix, zero bytes payload). To receive, you'd read 4 bytes, then interpret the payload length, then read that-many bytes.

    Alternatively, and probably the way I'd recommend you to go: use a library that handles this for you. For example, gRPC.