private void ProcessAccept(SocketAsyncEventArgs e) { SocketAsyncEventArgs readEventArgs = this._readWritePoolTcp.Pop(); ((AsyncUserToken)readEventArgs.UserToken).Socket = e.AcceptSocket; var connection = new TcpConnection(((AsyncUserToken)readEventArgs.UserToken).Socket); this.Logger.Trace( $"TCP Client Connected. IP: {(connection.Socket.RemoteEndPoint as IPEndPoint).Address}"); this.Connections.Add(connection); this.ClientConnected?.Invoke(this, new TcpConnectionConnectedEventArgs(connection)); bool willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs); if (!willRaiseEvent) { this.ProcessReceive(readEventArgs); } this.StartAccept(e); }
public TcpConnectionDisconnectedEventArgs(TcpConnection connection) { this.Connection = connection; }
public INetworkerServer Start() { if (this.configuration.UseTcp) { this.Logger.Trace($"Starting TCP Listener on port {this.configuration.TcpPort}."); this._tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this._tcpSocket.Bind(new IPEndPoint(IPAddress.Parse(this.configuration.IpAddresses[0]), this.configuration.TcpPort)); this._tcpSocket.Listen(this.configuration.Advanced.MaxTcpConnections); new Thread(() => { while (this._isRunning) { if (this._tcpSocket.Poll(10, SelectMode.SelectRead)) { var acceptedSocket = this._tcpSocket.Accept(); var connection = new TcpConnection(acceptedSocket); this.Logger.Trace( $"TCP Client Connected. IP: {(connection.Socket.RemoteEndPoint as IPEndPoint).Address}"); this.Connections.Add(connection); this.ClientConnected?.Invoke(this, new TcpConnectionConnectedEventArgs(connection)); } } }).Start(); new Thread(() => { while (this._isRunning) { foreach (var connection in this.Connections.ToList()) { if (!connection.Socket.Connected) { this.Logger.Trace( $"TCP Client Disconnected. IP: {(connection.Socket.RemoteEndPoint as IPEndPoint).Address}"); this.Connections.Remove(connection); this.ClientDisconnected?.Invoke(this, new TcpConnectionDisconnectedEventArgs(connection)); continue; } if (connection.Socket.Poll(10, SelectMode.SelectRead)) { var packets = this.packetDeserializer .GetPacketsFromSocket(connection.Socket); foreach (var packet in packets) { this.HandlePacket(connection, packet.Item1, packet.Item2); } } } } }).Start(); } if (this.configuration.UseUdp) { this.Logger.Trace($"Starting UDP Listener on port {this.configuration.UdpPortLocal}."); this.Logger.Trace($"Starting UDP Sender on port {this.configuration.UdpPortRemote}."); this._udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); this._udpClient = new UdpClient(this.configuration.UdpPortLocal); new Thread(() => { while (this._isRunning) { var result = this._udpClient.ReceiveAsync() .Result; var packets = this.packetDeserializer.GetPacketsFromUdp(result); foreach (var packet in packets) { this.HandlePacket(new UdpConnection(this._udpSocket, result), packet.Item1, packet.Item2); } } }).Start(); } return(this); }