tags:

views:

1377

answers:

3
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?

A: 

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?

Gee
+2  A: 

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.

Idan K
A: 

Oh well, I am getting Socket.Connected == false every time after the first few sends and receives, even though the connection is still open and both sides are happily exchanging data. There are definitely Receive() and Send() operations going on and succeeding and the data reach the other side, and yet (from some point on) Socket.Connected always returns false. Microsoft .Net Framework 4.

Barbara