TCP/IP detect if there is a currently connected client on a listener

左心房为你撑大大i 提交于 2019-12-24 14:04:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!