据我了解,这些行:
var client = await listener.AcceptTcpClientAsync();
var client = listener.AcceptTcpClient();
应该以相同的方式工作,但如果我尝试打开,例如,5k 连接(不关闭它们),很快监听器(异步)要么停止响应,要么抛出异常。
有人知道可能出了什么问题吗?
示例类:
class ListenerTest
{
static int connectionNumber = 0;
static int port = 23456;
public void StartListening(bool async)
{
var listener = new TcpListener(IPAddress.Any, port);
listener.Start();
if (async)
{
var task = HandleConnectionsAsync(listener);
task.Wait();
}
else
HandleConnections(listener);
}
async Task HandleConnectionsAsync(TcpListener listener)
{
while (true)
{
Console.Write("Waiting for async connection...");
var client = await listener.AcceptTcpClientAsync();
Console.WriteLine("OK #" + connectionNumber);
connectionNumber++;
}
}
void HandleConnections(TcpListener listener)
{
while (true)
{
Console.Write("Waiting for sync connection...");
var client = listener.AcceptTcpClient();
Console.WriteLine("OK #" + connectionNumber);
connectionNumber++;
}
}
public static void ConnectTest(int count)
{
var ep = new IPEndPoint(IPAddress.Loopback, port);
for (var i = 0; i < count; i++)
new TcpClient().Connect(ep);
}
}
用法:
static void Main(string[] args)
{
var isAsync = true;
ThreadPool.QueueUserWorkItem(new WaitCallback(StartListening), isAsync);
ListenerTest.ConnectTest(5000);
}
static void StartListening(object state)
{
var my = new ListenerTest();
my.StartListening((bool)state);
}