How does NetworkStream work in two directions?

后端 未结 3 1763
猫巷女王i
猫巷女王i 2021-01-20 13:39

I\'ve read an example of a Tcp Echo Server and some things are unclear to me.

TcpClient client = null;
NetworkStream netStream = null;

try {
  client = list         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-20 14:43

    Hint: The method call NetworkStream.Read is blocking in that example.

    The book is absolutely correct -- raw access to TCP streams does not imply any sort of extra "chunking" and, in this example for instance, a single byte could easily be processed at a time. However, performing the reading and writing in batches (normally with exposed buffers) can allow for more efficient processing (often as a result of less system calls). The network layer and network hardware also employ there own forms of buffers.

    There is actually no guarantee that data written from Write() will actually be written before more Reads() successfully complete: even if data is flushed in one layer it does not imply it is flushed in another and there is absolutely no guarantee that the data has made its way back over to the client. This is where higher-level protocols come into play.

    With this echo example the data is simply shoved through as fast as it can be. Both the Write and the Read will block based upon the underlying network stack (the send and receive buffers in particular), each with their own series of buffers.

    [This simplifies things a bit of course -- one could always look at the TCP [protocol] itself which does impose transmission characteristics on the actual packet flow.]

提交回复
热议问题