private void ProcessAccept(SocketAsyncEventArgs e) { SocketAsyncEventArgs socketAsyncEventArgs = null; try { if (this.Paused) { this.logger.Warn("Pause state. Connection pending ...", this.m_semaphore.CurrentCount); this.m_resumeEvent.WaitOne(); } IPAddress address = ((IPEndPoint)e.AcceptSocket.RemoteEndPoint).Address; if (ClientManager.MaxIPConnexions.HasValue && this.CountClientWithSameIp(address) > ClientManager.MaxIPConnexions.Value) { this.logger.Error <string, int>("Client {0} try to connect more then {1} times", e.AcceptSocket.RemoteEndPoint.ToString(), ClientManager.MaxIPConnexions.Value); this.m_semaphore.Release(); this.StartAccept(); } else { socketAsyncEventArgs = this.PopSocketArg(); BaseClient baseClient = this.m_createClientDelegate(e.AcceptSocket); socketAsyncEventArgs.UserToken = baseClient; lock (this.m_clients) { this.m_clients.Add(baseClient); } this.NotifyClientConnected(baseClient); baseClient.BeginReceive(); this.StartAccept(); } } catch (Exception argument) { this.logger.Error <EndPoint, Exception>("Cannot accept a connection from {0}. Exception : {1}", e.RemoteEndPoint, argument); this.m_semaphore.Release(); if (socketAsyncEventArgs != null) { this.PushSocketArg(socketAsyncEventArgs); } if (e.AcceptSocket != null) { e.AcceptSocket.Disconnect(false); } this.StartAccept(); } }
/// <summary> /// Called when a new client is connecting /// </summary> /// <param name="e"></param> private void ProcessAccept(SocketAsyncEventArgs e) { BaseClient client = null; try { // do not accept connections while pausing if (Paused) { logger.Warn("Pause state. Connection pending ...", m_semaphore.CurrentCount); // if paused wait until Resume() is called m_resumeEvent.WaitOne(); } try { if (e.AcceptSocket.RemoteEndPoint == null) { logger.Error("Invalid remote end-point (null)"); m_semaphore.Release(); return; } var IP = ((IPEndPoint)e.AcceptSocket.RemoteEndPoint).Address; if (MaxIPConnexions.HasValue && CountClientWithSameIp(IP) > MaxIPConnexions.Value) { logger.Error("Client {0} try to connect more then {1} times", e.AcceptSocket.RemoteEndPoint.ToString(), MaxIPConnexions.Value); m_semaphore.Release(); return; } } catch (Exception ex) { logger.Error("Invalid remote end-point {1}. Exception : {0}", ex, e.AcceptSocket.RemoteEndPoint); m_semaphore.Release(); return; } // use a async arg from the pool avoid to re-allocate memory on each connection // create the client instance client = m_createClientDelegate(e.AcceptSocket); lock (m_clients) m_clients.Add(client); NotifyClientConnected(client); client.BeginReceive(); } catch (Exception ex) { // if an error occurs we do our possible to reset all possible allocated ressources logger.Error("Cannot accept a connection from {0}. Exception : {1}", e.RemoteEndPoint, ex); if (client != null) { OnClientDisconnected(client); } else { m_semaphore.Release(); if (e.AcceptSocket != null) { if (e.AcceptSocket.Connected) { e.AcceptSocket.Disconnect(false); } } } } finally { StartAccept(); } }