I am building a Client/Server application in VB.NET 2008. I am looking for the best way to detect when a connection is dropped (not when the server program explicitly disconnects the client, but when the line is ‘cut’).
I do not want to make a custom protocol for sending and receiving packets every few seconds to detect if the connection is still available.
The NetworkChange.NetworkAddressChanged event detects only when the client unplugs his own network cable. It is not useful if the line is dropped somewhere else between the client and the server.
I know the sockets have a KeepAlive option:
myTcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, 1)
but is very little documentation.
I need an implementation of this in VB.NET 2008, or an solution of any kind for raising an event when the connection is dropped somewhere else between the client and the server.
Here is how my code works:
Uses a TcpClient and starts an asynchonus BeginRead, with a DoRead callback that executes when data is received.
Has a base class for a client, that is instanced for each new connection. This class also uses async BeginRead to receive data.
So, everything is asynchronus, and I do not want to use synchronus 'Receive' calls.
I have to trouble only when the network connection is dropped, not when the connection is explicitly closed either by the client or the server, because in this case I get an exception and I know the connection has closed.
Not sure if you've seen this from MSDN: TCP keepAlive settings problem. Near the end of the page is VB.NET version Private Function SetKeepAlive(ByVal sock As Socket, ByVal time As ULong, ByVal interval As ULong) As Boolean which sets (after setting TcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, 1)) also TcpClient.Client.IOControl(IOControlCode.KeepAliveValues, <inValue>, <outvalue>) i.e. low-level options for socket.
If I understood the whole thing correctly, it should now raise (on the server side) an event if the connection drops. I suggest reading the whole page and all the comments.