有没有办法限制tcpListener可以接受的客户端数量?
答案 0 :(得分:4)
如果你有太多人数,不要接受();
答案 1 :(得分:1)
您可以在事件处理程序中对其进行统计
class Server()
{
private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
public void Start()
{
TcpListener listener = new TcpListener(IPAddress.Any, 5555);
listener.Start();
while(true)
{
IAsyncResult result = tcpListener.BeginAcceptTcpClient(HandleAsyncConnection, tcpListener);
connectionWaitHandle.WaitOne(); //Wait until a client has begun handling an event
}
}
private void HandleAsyncConnection(IAsyncResult result)
{
TcpListener listener = (TcpListener)result.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(result);
connectionWaitHandle.Set(); //Inform the main thread this connection is now handled
//... Use your TcpClient here
client.Close();
}
}