C # Socket.Connected property is replaced with false after calling Socket.Receive

int readCount; byte[] buffer = new byte[128]; SocketError socketError; TcpClient tcpClient = tcpListener.AcceptTcpClient(); tcpClient.Client.ReceiveTimeout = 500; // #1 // tcpClient.Client.Connected is **true** here. readCount = tcpClient.Client.Receive(buffer, 0, buffer.Length, SocketFlags.None, out socketError); // reacCount > 0 // tcpClient.Client.Connected is **false** here. 

If # 1 is replaced by tcpClient.Client.Blocking = false; , tcpClient.Client.Connected has the correct value (true).


I set the Socket.ReceiveTime property to 100 and called Socket.Receive() . Receive() returned integer value is greater than zero. There was no exception. After doing my work with the copied buffer — I did not use any of the socket-related methods — the Socket.Connected property was changed to false. Why?

+4
source share
2 answers

The key may be that TcpClient.Connected is valid:

The Connected property retrieves the client socket connection status from the last I / O operation . When this returns false, the client socket was either not connected or no longer.

Since only the Connected property reflects the state of the connection as of the most recent operation, you should try to send or receive a message to determine the current state. After a message is sent with an error, this property no longer returns true. Please note that this is a design behavior. You cannot reliably check the status of the connection, because at the time between the test and the send / receive, the connection could be lost. Your code should assume that failed transfers are gracefully handled and gracefully handled.

So, when you are not blocking, and by the time you check the Connected value, the reading may not have been completed, so Connected still has the old value.

+5
source

This can happen if the remote host is no longer connected to the socket. Is there a timeout on the other side of the connection that could be exceeded?

0
source

Source: https://habr.com/ru/post/1286397/


All Articles