How to determine if a client has closed a connection ?

M

Magne Ryholt

Assume a TcpListener has accepted a client connection
(TcpListener.AcceptTcpClient()), then it should write text lines until the
client has closed the connection,
after the client has closed, then the server shall close on it's side.

I am using a StreamWriter on the NetWorkStream on the TcpClient
(StreamWriter sw = new StreamWriter(tcpClient.GetStream());)

Is the only way to determine if the client has closed the connection on his
side, to catch an IOException on StreamWriter.Flush() method ?
Should it not be possible to monitor the StreamWriter, NetworkStream,
TcpClient or the underlying Socket to check if the client has closed ?
 
G

Girish Bharadwaj

You can probably use TcpClient.Client.Connected property to determine if you
are connected.
 
M

Magne Ryholt

Thanks for your answer, however I think this will not work properly.
The TcpClient.Client property is protected which means that I have to derive
a new class from TcpClient and add some property/method to check the
Socket's Connected property.
This is ok, but then I also have to derive from TcpListener and override
AcceptClient() to return an object of my class derived from TcpClient ( in
order to avoid using the lower level Socket class), I don't know how to do
this.
Perhaps it is an easy way to do this, but still I don't think it will work,
ref doc. for Socket.Connected property, this property reflects the state of
the socket at the time of the last I/O operation, which means that I have to
send something to a closed socket in order to find out that the socket is
closed, it's a bit too late (the IOException would be thrown before the
execution reaches this far)

Please correct me if I am wrong.
 
G

Girish Bharadwaj

You are right. I was thinking you might be able to do AcceptSocket() instead
of AcceptTcpClient() and use the socket to determine the "Connected" state.
But, even there, it looks like that state only represents the last known
state and not the current state.

The one think to consider is , if you can use AcceptSocket(), is to use
Socket.Poll() method with SelectWrite to find out if you can send data to
that socket...
Maybe, it helps?
 

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