Hello,
I have a tcplistener and a tcpclient. If the client computer went down for some reason, what would be the best way to handle disconnections.
Thanks in advance,
Minko
Hello,
I have a tcplistener and a tcpclient. If the client computer went down for some reason, what would be the best way to handle disconnections.
Thanks in advance,
Minko
Since marked this solved, here is a concise, practical checklist and a couple of small VB.NET snippets that show the reliable ways to detect and handle a client disconnect when using TcpListener/TcpClient.
Prefer detecting end-of-stream rather than checking Connected: a NetworkStream.Read that returns 0 bytes means the remote closed the connection gracefully (NetworkStream.Read docs). Non-blocking detection can use the socket Poll + Available check; Poll(..., SelectMode.SelectRead) with Available = 0 is a common indicator of a disconnect (Socket.Poll docs). Do not rely on Socket.Connected alone because it can be stale (Socket.Connected docs).
Minimal VB.NET examples:
' read-end detection
Dim bytes = stream.Read(buffer, 0, buffer.Length)
If bytes = 0 Then
' client closed connection
client.Close()
End If ' poll + available (non-blocking)
If client.Client.Poll(1000, SelectMode.SelectRead) AndAlso client.Client.Available = 0 Then
' treat as disconnected
End If Also:
SocketException and IOException around reads/writes; treat these as disconnection or network error signals. SetSocketOption, but prefer an app heartbeat for predictable timing (Socket.SetSocketOption docs).Always close and dispose sockets and cancel any background loops when a disconnect is detected.
I managed to sort this out so I will mark this as solved.
Minko
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.