问题
Is there any way for my TCP/IP listener to detect if there are currently conencted client?
This is my code:
Public Sub StopListen()
client.Close()
tcpClientThread.Abort()
server.Stop()
SyncLock accessLock
endThread = True
End SyncLock
Btn_Listen.Text = "Listen"
End Sub
The problem in that code is whenever the user pressed the Stop Listen
button and there are currently no cients connected to my listener an error occurs.
How can I do something like this?
Public Sub StopListen()
If thereIsConnectedClient Then
client.Close()
End If
tcpClientThread.Abort()
server.Stop()
SyncLock accessLock
endThread = True
End SyncLock
Btn_Listen.Text = "Listen"
End Sub
回答1:
Generally speaking, after the SYNC-SYNC,ACK-ACK three way handshake, the connection is established and TcpListener returns a tcpClient. This tcpClient can be kept in an array. The number of elements in this array represents the number of connections.
In the normal scenario, after server and client exchange data packets, either the server or the client will initiate a FIN request. After the FIN-ACK,FIN-ACK flags are exchanged, connection finished and that tcpClient can be removed from the array.
Now if there are clients not actively closing the socket, then the server may need an mechanism to disconnect the inactive socket. Either by having a timeout on the connection. Or periodically send some empty packet and wait for the ACK from the remote client to decide whether the client is still present.
来源:https://stackoverflow.com/questions/31978697/tcp-ip-detect-if-there-is-a-currently-connected-client-on-a-listener