Socket.Listen
方法:
Listen会导致... Socket监听传入的连接尝试。 backlog参数指定可以排队等待接受的传入连接数...使用Accept或BeginAccept接受队列中的连接。
这意味着套接字会将传入连接放入队列中。我们如何确定排队连接的数量?
var localEndPoint = new IPEndPoint(IPAddress.Any, Port);
var serverSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
serverSocket.Bind(localEndPoint);
// listen for incoming connections; queue `socketBacklog` of them
// Listen bit.ly/21vz22b
serverSocket.Listen(socketBacklog);
// how do we do this?
serverSocket.CountQueuedConnections()
我尝试过的一件事显然不起作用,serverSocket.Poll(timeToWait, SelectMode.SelectRead)
。这总是返回false
。
答案 0 :(得分:1)
以MSDN的套接字代码示例为例:
Asynchronous Server Socket Example
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(100);
while (true) {
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener );
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
在此代码中,您可以在无限循环内轻松添加计数器,以确定已连接到服务器的客户端数量。
Socket.Listen Method (Int32)
仅提供可以连接到此ServerSocket的最大客户端数。此外,Listen不会阻止。