private void AcceptCompleted(SocketAsyncEventArgs args, bool startMore) { Interlocked.Increment(ref totalConnections); Socket newSocket = null; try { newSocket = args.AcceptSocket; if (doNotAccept) { Kill(newSocket); } else { #if VERBOSE Debug.WriteLine(string.Format("[{0}]\taccepted: from {1} to {2}", this, newSocket.RemoteEndPoint, newSocket.LocalEndPoint)); #endif args.AcceptSocket = null; // clear ASAP to avoid accidental re-use ThreadPool.QueueUserWorkItem(delegate { var state = ProtocolFactory.CreateConnection(newSocket.LocalEndPoint) ?? new Connection(); state.Prepare(); // logs LastSeen; generates new id // WriteLog("accepted from " + newSocket.RemoteEndPoint + " to " + newSocket.LocalEndPoint, state); var processor = ProtocolFactory.GetProcessor(); state.SetProtocol(processor); processor.InitializeInbound(Context, state); state.Socket = newSocket; #if DEBUG && LOG_OUTBOUND state.ResetLogOutput(); #endif OnAccepted(state); }); } } catch (Exception ex) { Logger?.Error(ex, $"{Connection.GetIdent(args)}\tAccept"); Kill(newSocket); } if (startMore) { StartAccept(args); // look for other clients too } }