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
Greatly appreciate any assistance.
Thanks
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
Thanks