开发者

how to constrain the number of clients a TcpListener can accept?

开发者 https://www.devze.com 2022-12-16 10:42 出处:网络
is there a way to limit the number of clients a tcpListene开发者_如何学运维r can accept?Count them and dont accept() if you have too many?You can count it in your event handlerclass Server()

is there a way to limit the number of clients a tcpListene开发者_如何学运维r can accept?


Count them and dont accept() if you have too many?


You can count it in your event handler

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

} }

0

精彩评论

暂无评论...
验证码 换一张
取 消