/// <summary> /// Begins listening for requests. /// </summary> /// <param name="cancellationToken">A token to observe for cancellation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous listening operation.</returns> public Task StartAsync(CancellationToken cancellationToken) { Task.Run(async() => { try { this.tcpListener.Start(); // Stop() makes AcceptSocketAsync() throw an ObjectDisposedException. // This means that when the token is cancelled, the callback action here will be to Stop() the listener, // which in turn throws the exception and it gets caught below, exiting gracefully. cancellationToken.Register(() => this.tcpListener.Stop()); while (!cancellationToken.IsCancellationRequested) { try { var socket = await this.tcpListener.AcceptSocketAsync().ConfigureAwait(false); ISocketConnection socketConnection = this.socketConnectionFactory.Create(socket); if (this.dosDefender?.IsBlocked(socketConnection.SocketIp) ?? false) { // TODO: evaluate if it is worth just leaving the connection open but ignore it, so that they think they are successfully DoSing... // But we would need to think if it is a connection drain attack then... socketConnection.Close(); continue; } this.NewConnection?.Invoke(socketConnection); socketConnection.Closed += this.OnConnectionClose; socketConnection.PacketProcessed += this.AfterConnectionMessageProcessed; this.dosDefender?.LogConnectionAttempt(socketConnection.SocketIp); socketConnection.Read(); } catch (ObjectDisposedException) { // This is normal when the listerner is stopped because of token cancellation. break; } catch (Exception socEx) { this.Logger.Error(socEx.ToString()); } } } catch (SocketException socEx) { this.Logger.Error(socEx.ToString()); } }); // return this to allow other IHostedService-s to start. return(Task.CompletedTask); }
public void Close() { _socket?.Close(); _socket = null; _mouseSocket?.Close(); _mouseSocket = null; }
public void Dispose() { _isDisposed = true; _keepAliveTimer.Enabled = false; _keepAliveTimer.Stop(); _packetProtocol.MessageArrived = null; _packetProtocol.KeepAliveArrived = null; _socket.Disconnect(false); _socket.Dispose(); _socket.Close(); }