Results 1 to 9 of 9

Thread: TCP Listener detect when client disconnects

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    65

    Question TCP Listener detect when client disconnects

    Hi all,

    I have an application that accepts connections on a given port using a thread. I'm trying to work out the best way to detect of a client has disconnected. I don't want to rely on a message from the client eg "quit" to notify my application a client has dropped off. Id like to be able to detect it in a smarter way, but just not sure how.

    I have 2 main bits of code

    Code:
        Private Sub RemoteClientListen()
    
            Dim myport = TCPListenPort
    
            listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, myport) 'The TcpListener will listen for incoming connections        
            Try
                listener.Start() 'Start listening.        
            Catch excep As System.Net.Sockets.SocketException
                MessageBox.Show(excep.Message, excep.Source)
            End Try
    
            listenThread = New System.Threading.Thread(AddressOf DoListen) 'This thread will run the doListen method        
            listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.        
            listenThread.Start() 'Start executing doListen on the worker thread.    
            UpdateStatus("TCP Server - Active on port: " & myport)
    
        End Sub
    
        Private Sub DoListen()
            Try
                Dim incomingClient As System.Net.Sockets.TcpClient
                Do
                    incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.            
    
                    networkStream = incomingClient.GetStream()
                    Dim ipEndPoint As IPEndPoint = incomingClient.Client.RemoteEndPoint
                    ipClientAddress = ipEndPoint.Address
    
                    Dim connClient As New ConnectedClient(incomingClient, Me, ipClientAddress.ToString) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
                    AddHandler connClient.dataReceived, AddressOf Me.MessageReceived
                    connClient.Username = ipClientAddress.ToString
    
                    AddClientToListBox(ipClientAddress.ToString)
                    clients.Add(connClient) 'Adds the connected client to the list of connected clients.
    
                    UpdateStatus("Client Connected:" & ipClientAddress.ToString)
    
                Loop
    
            Catch
            End Try
        End Sub
    Greatly appreciate any assistance.

    Thanks

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: TCP Listener detect when client disconnects

    I don't think that you can know that a client is no longer there until you try to communicate with it. You might then send a heartbeat message to a client and catch the exception that is thrown if the client is no longer connected.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    65

    Re: TCP Listener detect when client disconnects

    Thanks for the quick reply! So I should perhaps run some code in a timer that does as you've suggested?
    Would you be able to post some code to set me in the right direction?

    Cheers

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: TCP Listener detect when client disconnects

    Quote Originally Posted by BassTeQ View Post
    Thanks for the quick reply! So I should perhaps run some code in a timer that does as you've suggested?
    Yep.
    Quote Originally Posted by BassTeQ View Post
    Would you be able to post some code to set me in the right direction?
    Nope. It's just sending data from the server to the client the same way you would send any data. You should already have exception handling in place for that so nothing changes. You'll just want to decide on a small, unusual series of bytes to represent the heartbeat so that the client knows what it is and to ignore it.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Lively Member
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    65

    Re: TCP Listener detect when client disconnects

    Problem is I'm replacing/rewitting an old application I don't have the source to, but I've worked out what data it sends/receives. I cant modify the client application so sending a magic packet wont work either.
    Stuck in a bind Was hoping there was a way to check at the lower network level if the connection had become broken.

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: TCP Listener detect when client disconnects

    You might be able to get some information from the TcpClient's underlying Socket, although I've never tried. I'd suggest reading the documentation for the Socket class to see if you can see anything. For instance, the Poll method might be useful but I've never used it myself.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: TCP Listener detect when client disconnects

    Well, I've had success detecting disconnects by wrapping a call to Receive in an exception handler. It won't catch disconnects caused by unplugging your network cable though. You have to attempt a send to detect that. All in all, what jmc says is about the only real way to detect disconnects. The problem is not with the socket implementation but rather the TCP/IP protocol itself. It is designed to be quite a tolerant protocol and as a result we have these issues.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,104

    Re: TCP Listener detect when client disconnects

    Another point about TCP is that the connection isn't really always open. It isn't like plugging a cord into an outlet where you can determine that the cord is plugged in by checking the voltage on the line. There isn't really any constant connection in the network, though the TCP protocol makes it look like there is. What is really happening is that it is maintaining the destination, taking all messages, dividing them as needed, sequencing them, sending them, and receiving messages. It adds enough overhead that the receiver can stitch the message back together and can know whether or not it received the whole message, but there isn't any kind of complete circuit, it's still just independent packets sent out onto the wire individually and rather anonymously. One of the basic tenets of the internet is that the packets that make up any particular message don't have to travel in any one particular route, nor do they all have to take the same route, nor do they even have to remain as single packets. Routers along the route can take a single packet and divide it into pieces, and all pieces of a message can take different routes. So, there really isn't any kind of physical connection. It is nothing more than a virtual connection that is made to look like a physical connection by the protocol. In such a system, you can't ever be sure there is a listener until you don't hear anything back. Therefore, you can only detect a connection while the connection is handling traffic, and can't detect the status of the connection when there is no traffic. So you have to send to know.
    My usual boring signature: Nothing

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    65

    Re: TCP Listener detect when client disconnects

    Quote Originally Posted by Niya View Post
    Well, I've had success detecting disconnects by wrapping a call to Receive in an exception handler. It won't catch disconnects caused by unplugging your network cable though. You have to attempt a send to detect that. All in all, what jmc says is about the only real way to detect disconnects. The problem is not with the socket implementation but rather the TCP/IP protocol itself. It is designed to be quite a tolerant protocol and as a result we have these issues.
    That sounds like a good idea, I'll give that a try!

    I've put together something yesterday that also works by using IPGproperties.GetActiveTcpConnections(), then I just check that the connection for a given IP is still Established, if not I'll assume its disconnected. Seems to work reasonably well.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width