Пример #1
0
        private void AddSocketSession(Socket client)
        {
            if (client == null)
            {
                return;
            }

            lock (ChannelManager.SyncLock)
            {
                ISocketAsyncEventArgsProxy socketProxy = this._SocketAsyncPool.Pop();
                if (socketProxy == null)
                {
                    AsyncUtil.AsyncRun(client.SafeClose);
                    Logger.Info(false, "已经到达最大连接数");
                    return;
                }

                ISocketSession socketSession = new SocketSession(client, socketProxy);
                socketSession.Setup(this);
                socketSession.Initialize();

                if (ChannelManager.AddChannel(socketSession.SessionID, socketSession))
                {
                    socketSession.CloseSocket += socketChannel_CloseSocket;
                    if (Config.ControlMode == ControlMode.Self ||
                        Config.ControlMode == ControlMode.Parallel ||
                        Config.ControlMode == ControlMode.Singleton)
                    {
                        socketSession.SocketReceiveData += socketChannel_SocketReceiveData;
                        AsyncUtil.AsyncRun(socketSession.TryReceive);
                    }

                    OnSocketConnected(socketSession.RemoteIP, socketSession.RemotePort);

                    OnChannelChanged(socketSession.RemoteIP, CommunicateType.NET, ChannelState.Open);
                }
                else
                {
                    ISocketAsyncEventArgsProxy proxy = socketSession.SocketAsyncProxy;
                    proxy.Reset();
                    if (proxy.ReceiveOffset != proxy.SocketReceiveEventArgs.Offset)
                    {
                        proxy.SocketReceiveEventArgs.SetBuffer(proxy.ReceiveOffset, Config.NetReceiveBufferSize);
                    }
                    _SocketAsyncPool.Push(proxy);
                    socketSession.Close();
                    socketSession = null;
                    Logger.Info(true, "增加网络连接实例失败");
                }
            }
        }