如何约束TcpListener可以接受的客户端数量?

时间:2010-01-13 14:32:30

标签: c# tcplistener

有没有办法限制tcpListener可以接受的客户端数量?

2 个答案:

答案 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();

} }