代码之家  ›  专栏  ›  技术社区  ›  Benny

如何限制tcplistener可以接受的客户机数量?

  •  0
  • Benny  · 技术社区  · 15 年前

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

    2 回复  |  直到 15 年前
        1
  •  4
  •   user181351    15 年前

    数一数,如果你有太多的话就不要接受()?

        2
  •  1
  •   Yevhen    15 年前

    您可以在事件处理程序中对其进行计数

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

    } }