views:

1154

answers:

4

I'm playing around with the TcpClient and I'm trying to figure out how to make the Connected property say false when a connection is dropped.

I tried doing

NetworkStream ns = client.GetStream();
ns.Write(new byte[1], 0, 0);

But it still will not show me if the TcpClient is disconnected. How would you go about this using a TcpClient?

A: 

use the Connected property of TcpClient.

if (client.Connected)
{
   ns.Write(new byte[1], 0, 0);
}
else
{
   // disconnected
}

Edit

According to a similar discussion, the Connected property does not represent the real-time status of the connection, but the status at the last read\write operation.

Aziz
Thats basicly what I have been doing to no avail
Superdumbell
I have been calling the ns.Write first then checking the client.Connected inside of a Timer and it never shows that it has disconnected even though the remote host was shutdown.
Superdumbell
Indeed the Connected property is not reliable. So what is it good for ? Some sort of early foundation for .net 4 ?
Jelly Amma
It can tell you if your last connection was successful. This can be useful information.
Jess
+1  A: 

As far as I know/remember there is no way to test if a socket is connected other than reading or writing to it.

I haven't used the TcpClient at all but the Socket class will return 0 from a call to Read if the remote end has been shutdown gracefully. If the remote end doesn't shutdown gracefully [I think] you get a timeout exception, can't remember the type sorry.

Using code like 'if(socket.Connected) { socket.Write(...) } creates a race condition. You're better off just calling socket.Write and handling the exceptions and/or disconnections.

Keith Moore
Gee, talk about vague, sorry. I shouldn't answer questions at 6:30pm right before I'm going home.
Keith Moore
Yeah. Socket layer shall managed using exceptions. The IOException thrown has the inner exception set to a SocketException, which contains all information required to detect timeouts or closed sockets remotely.
Luca
A: 

what about buffer ? in case you should test periodcally won't it cause an overflow ? is there a solutuion to clear buffer after write?

Angelo
+1  A: 

Also you can use TcpClient's canwirte property before write out
look http://msdn.microsoft.com/tr-tr/library/system.net.sockets.tcpclient.getstream.aspx has a detailed sample

dankyy1