开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜