TcpClient; NetworkStream; ReadAsync; C#

左心房为你撑大大i 提交于 2019-12-04 14:12:13

No, that's not how TCP works.

NetworkStream is considered to be in an "end of stream" state when the other side has initiated (possible one-way) shutdown. That's when ReadAsync (or Read, for that matter) returns zero - not in any other case.

The MSDN documentation can be easily misunderstood - mainly because you're looking at the wrong piece of documentation. NetworkStream doesn't override ReadAsync (there's no reason to do so), so you're actually looking at the documentation for the generic Stream.ReadAsync. In contrast, the documentation for NetworkStream.Read says:

This method reads data into the buffer parameter and returns the number of bytes successfully read. If no data is available for reading, the Read method returns 0. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter. If the remote host shuts down the connection, and all available data has been received, the Read method completes immediately and return zero bytes.

Note the final sentence, which tells you what it actually means for a NetworkStream to be "end of stream". This is how TCP connections are closed.

Your response to this should usually be shutting down the connection from the other side as well - return out of your helper method and clean up the socket. In any case, do not repeat the while (true) again - you're just going to get an infinite loop that eats 100% of your CPU.

If you want a few pointers on how to handle C# asynchronous sockets with await, have a look at my sample at https://github.com/Luaancz/Networking/tree/master/Networking%20Part%202. Note the disclaimers - this is in no way production ready. But it does solve a few of the very common mistakes people make when implementing TCP communication.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!