In my multi-threading server app, a thread per client is generated in this way:
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
log.debug("Client No: " + Convert.ToString(counter) + " started!")
Dim client As New handleClinet
clients.Add(clientSocket)
client.startClient(clientSocket, Convert.ToString(counter))
End While
and in handleClinet:
Public Sub startClient(ByVal inClientSocket As TcpClient, ByVal clineNo As String)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Name = "client" + clineNo
ctThread.Start()
End Sub
As you can see, the thread is made with the name client1, client2, etc. When a user signs out, a command is send to the server along with the clientID. But how can I kill the specific client process?
Something like:
Public Sub killClient(ByVal clientID As Int32)
'Code to kill "client"+clientID
End Sub
Threads are just execution vehicles. Any time you think you need to push a thread around, think instead about what the thread is doing. When you don’t need your doctor anymore, you don’t kill him. You leave his office.
If you want to shut down the client cleanly, set a ‘shutdown’ flag in the client structure. Have the code that handles the client check this flag periodically. Forget about what thread is doing it, it’s the client you want to shut down.
If that’s too passive, shutdown the TCP connection to the client. That will cause any code that touches the client’s connection to get an error.
Forget about the fact that it happens to be a dedicated thread that’s handling the client. You wrote the code. Code it so that it stops handling the client when that’s no longer appropriate by checking if it’s appropriate to handle a client before handling it.