TcpClient.Connected returns true, but the client is not connected, what can I use instead?

In VB.net, I use TcpClient to retrieve a data string. I constantly check the .Connected property to check if the client is connected, but even if the client disconnects, it 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 suggest that at least a call to GetStream () would throw an exception if the client was disconnected, but I closed another application and it still doesn't ...

Thanks.

EDIT Customer survey. Presumably, but this did not solve the problem. If the client does not have access to "acutally", it simply returns 0.

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

+4
source share
4 answers

When NetworkStream.Read returns 0, the connection is closed. Link :

If data is not 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 has been placed in the incoming network buffer for reading. If the DataAvailable returns true, the Read operation will complete immediately. A read operation will read as much data as is available, up to the number of bytes specified by the size parameter. If the remote node disconnects the connection and all available data has been received, the Read method will end immediately and return zero bytes.

+6
source

The best answer:

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

https://i.stack.imgur.com/Jb0X2.png

LINK = https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.poll?view=netframework-4.0

You need to set up a timer that from time to time sends messages to another socket.

Dim TC As New TimerCallback (AddressOf Ping)

Tick ​​= New Threading.Timer (TC, Nothing, 0, 30000)

 Sub Ping() Send("Stil here?") End Sub 
0
source

Instead of polling client.connected, you can use the NetworkStream properties to see if there is any data available?

Anyway, there is an ONDotnet.com article with TONS information about listeners and much more. If you help you overcome the problem ...

-1
source

Source: https://habr.com/ru/post/1276922/


All Articles