Exemplo n.º 1
0
        /// <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();
            }
        }