tags:

views:

1717

answers:

3

In VB.net I'm using the TcpClient to retrieve a string of data. I'm constantly checking the .Connected property to verify if the client is connected but even if the client disconnects this still returns true. What can I use as a workaround for this?

This is a stripped down version of my current code:

Dim client as TcpClient = Nothing
client = listener.AcceptTcpClient
do while client.connected = true
   dim stream as networkStream = client.GetStream()
   dim bytes(1024) as byte
   dim numCharRead as integer = stream.Read(bytes,0,bytes.length)
   dim strRead as string = System.Text.Encoding.ASCII.GetString(bytes,0,i)
loop

I would have figured at least the GetStream() call would throw an exception if the client was disconnected but I've closed the other app and it still doesn't...

Thanks.

EDIT Polling the Client.Available was suggested but that doesn't solve the issue. If the client is not 'acutally' connected available just returns 0.

The key is that I'm trying to allow the connection to stay open and allow me to receive data multiple times over the same socket connection.

A: 

Instead of polling client.connected, maybe use of the NetworkStream's properties to see if there's no more data available?

Anyhow, there's an ONDotnet.com article with TONS of info on listeners and whatnot. Should help you get past your issue...

Kevin Fairchild
+3  A: 

When NetworkStream.Read returns 0, then the connection has been closed. Reference:

If no data is available for reading, the NetworkStream.Read method will block until data is available. To avoid blocking, you can use the DataAvailable property to determine if data is queued in the incoming network buffer for reading. If DataAvailable returns true, the Read operation will complete immediately. The Read operation will read as much data as is available, up to the number of bytes specified by the size parameter. If the remote host shuts down the connection, and all available data has been received, the Read method will complete immediately and return zero bytes.

Mark Brackett
+1  A: 

Better answer:

  if (client.Client.Poll(0, SelectMode.SelectRead))
                    {
                        byte[] checkConn = new byte[1];
                        if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0)
                        {
                            throw new IOException();
                        }
                    }
Sean P