private static void DisconnectUser(PlayerConnection connection) { lock (locker) { if (connection != null) { if (connection.ConnectionSocket != null) { connection.ConnectionSocket.Close(); } if (EntityConnections.Contains(connection)) { EntityConnections.Remove(connection); connection.Dispose(); } } } }
private static void AcceptCallback(IAsyncResult result) { PlayerConnection connection = new PlayerConnection(); bool EntityError = false; try { // Finish accepting the connection. using (Socket s = (Socket)result.AsyncState) { connection.ConnectionSocket = s.EndAccept(result); connection.Buffer = new byte[connection.Buffer.Length]; lock (locker) { EntityConnections.Add(connection); } // Queue the receiving of data from the connection. connection.ConnectionSocket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); } } catch (Exception) { EntityError = true; } finally { if (EntityError) { DisconnectUser(connection); } // Accept the next incoming connection. _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), _serverSocket); } }