简体   繁体   中英

C# Socket.Connected property is changed to 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 with tcpClient.Client.Blocking = false; , tcpClient.Client.Connected has correct value(true).


I've set Socket.ReceiveTime property to 100 and invoked Socket.Receive() . Receive() returned integer value greater than zero. No exception occurred. After I do my job with copied buffer - I didn't user any of Socket related methods -, Socket.Connected property has been changed to false. Why?

The key might be in what TcpClient.Connected really does:

The Connected property gets the connection state of the Client socket as of the last I/O operation . When it returns false, the Client socket was either never connected, or is no longer 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.

So when you're not blocking and by the time you're checking the Connected value, it's possible the read wasn't finished therefore Connected is still at it's old value.

This might happen if the remote host is no longer connected to the socket. Is there a timeout on the other side of the connection which might've been exceeded?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM