开发者

C# BinaryReader.ReadString on a network socket

开发者 https://www.devze.com 2023-04-11 13:26 出处:网络
I have a server/client app. Both use BinaryReader/Writer when communicating. When the client and server are exchanging messages rapidly, many in a given second, and I shutdown the server (via a buil

I have a server/client app.

Both use BinaryReader/Writer when communicating.

When the client and server are exchanging messages rapidly, many in a given second, and I shutdown the server (via a built in command, orderly shutdown) most of the time (bu开发者_开发知识库t not always) the client's BinaryReader.ReadString() method throws a EndOfStreamException, which is fine. The thing that I don't understand is why doesn't this exception change the TcpClient.Connected property to 'false'?

while(true){
   try{
      BinaryReader.ReadString()
   }
   catch(IOException){
     if(!TcpClient.Connected)
        break;
     //BinaryWriter.Write() - this will, eventually, change Connected property to 'false'
   }
}

This will loop endlessly. I thought that the Connected property changes on unsuccessful network read/write. If BinaryReader is throwing exceptions then it isn't successfully reading, is it?

If I throw in a BinaryWriter.Write(), then the endless loop is broken because Connected property is changed to 'false'.

Related question, does an EndOfStreamException always indicate a broken network connection or could it mean a temporary problem?


By design. From the Remarks section of the MSDN Library article for TcpClient.Connected:

Because the Connected property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns true. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost. Your code should assume the socket is connected, and gracefully handle failed transmissions

The workaround you discovered is the correct one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号