private Task Handle(Guid guid, TcpClient client, AsyncTcpClientHandler handler, CancellationToken token) { return(Task.Run(async delegate { using (client) { try { await handler(client, token); } finally { _clients.TryRemove(guid, out _); _handlers.TryRemove(guid, out _); } } }, token)); }
private async Task AcceptAsync(AsyncTcpClientHandler handler, CancellationToken token) { while (!token.IsCancellationRequested) { TcpClient client; try { client = await _listener.AcceptTcpClientAsync(token); } catch (OperationCanceledException) { break; } var guid = Guid.NewGuid(); // Keep track of the connected clients. _clients.TryAdd(guid, client); // Queues the client connection handler to run on the thread pool. _handlers.TryAdd(guid, Handle(guid, client, handler, token)); } }
public async Task StartAcceptAsync(AsyncTcpClientHandler handler, CancellationToken token) { if (_listener != null) { throw new InvalidOperationException("The listener is already started"); } // Initialize all the listener resources. _listener = new TcpListener(_host, _port); _clients = new ConcurrentDictionary <Guid, TcpClient>(); _handlers = new ConcurrentDictionary <Guid, Task>(); // Accepts IPv4 and IPv6. _listener.Server.DualMode = true; // Start listening for incoming connections. _listener.Start(); // Register to stop any waiting listener. using (token.Register(async delegate { await StopAsync(); })) { await AcceptAsync(handler, token); } }