From what I understand, those lines:
var client = await listener.AcceptTcpClientAsync();
var client = listener.AcceptTcpClient();
should work the same way, but if I try to open, for example, 5k connections (without closing them), very soon listener (async) either stops responding or throws exception.
Anyone have idea what may be wrong?
Sample class:
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);
}
}
Usage:
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);
}