How to use the Socket "Connected" property properly?

D

Dr. J

I have an application that opens a socket and connects to another
application listening over a port. The problem I am encountering is that
when the listening application is closed my application cannot detect it to
take appropriate action. I am using "Connected" property of the Socket
class, but it seems this property does not reflect the true state of the
socket connection.

Here is the code snippet. Basically, I am checking the "Socket.Connected"
property in a while loop and want to drop out of the loop as soon as the
listening application is closed. The problem is when I close the listening
application, the while loop continues happily. Any suggestions on how to
make the Socket.Connected property to reflect true state of socket
connection? Any other ideas?

Thanks in advance,



Socket MySocket = null;
IPEndPoint Ep;

MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
Ep = new IPEndPoint(IPAddress, Port);

// connect to another application listening
MySocket.Connect (EpF);

while (MySocket.Connected )
{
// use socket to send/receive data
// Drop out of this loop if the listening
// application is closed.

}
 
I

Ian Griffiths [C# MVP]

Welcome to TCP...

The way you discover that the remote end has closed a connection is by
attempting to read from it. The read attempt returns no data, indicating
that the connection has closed.

This is not unique to .NET by the way - most sockets do this. (The same
issue exists on Linux for example.)

The reason for this is that because of the way TCP works, it is valid for
the client to continue to send data to the server even though the server may
have closed the connection at its end. All it really means for the server
to close the connection is that it is shutting down its ability to transmit
data to the client. The connection is in a state sometimes described as
'half-open'.

So that's it's the Read operation that tells you the server has closed the
connection - the fact that the server has closed its connection simply means
that you won't be receiving any more data from it. This is not necessarily
going to prevent you from sending it more data, which is why the connection
doesn't appear to be closed at this point.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top