private void socketLintener_DataReceived(object sender, ConnectionEventArgs e)
 {
     try
     {
         OnReceivedBefore(e);
         RequestPackage package;
         if (!ActionDispatcher.TryDecodePackage(e, out package))
         {
             return;
         }
         var session = GetSession(e, package);
         CheckSpecialPackge(package, session);
         package.Bind(session);
         //检查是否已连接路由服
         var switchSession = ServerSsMgr.GetSwitchSession();
         if (switchSession == null)
         {
             ProcessNotReady(package, session).Wait();
         }
         else
         {
             SendAsyncToSwitch(e, session.SessionId).Wait();
         }
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("Received to Host:{0} error:{1}", e.Socket.RemoteEndPoint, ex);
     }
 }
        /// <summary>
        /// 异步发送给路由服
        /// </summary>
        public async System.Threading.Tasks.Task SendAsyncToSwitch(ConnectionEventArgs e, string proxyId)
        {
            //转发给路由服,并通知路由服转发给大厅服
            var switchSession = ServerSsMgr.GetSwitchSession();
            var ssidStr       = HttpUtility.UrlEncode(string.Format("&proxyId={0}&proxyIp={1}", proxyId, e.Socket.RemoteEndPoint.ToString()));
            var ssidData      = Encoding.UTF8.GetBytes(ssidStr);
            var buffer        = new byte[e.Data.Length + ssidData.Length];

            Buffer.BlockCopy(e.Data, 0, buffer, 0, e.Data.Length);
            Buffer.BlockCopy(ssidData, 0, buffer, e.Data.Length, ssidData.Length);
            await switchSession.SendAsync(buffer, 0, buffer.Length);
        }
        /// <summary>
        /// 异步通知路由服客户端断开
        /// </summary>
        public async System.Threading.Tasks.Task SendSwitchClientDisconnect(GameSession session)
        {
            //转发给路由服,并通知路由服转发给大厅服
            var switchSession = ServerSsMgr.GetSwitchSession();

            if (switchSession == null)
            {
                return;
            }
            RequestParam interruptParam = new RequestParam();

            interruptParam["ActionId"] = (int)ActionEnum.Interrupt;
            interruptParam["MsgId"]    = 0;
            interruptParam["proxyId"]  = session.SessionId;
            string post   = string.Format("?d={0}", HttpUtility.UrlEncode(interruptParam.ToPostString()));
            var    buffer = Encoding.ASCII.GetBytes(post);
            await switchSession.SendAsync(buffer, 0, buffer.Length);
        }
        private GameSession GetSession(SocketEventArgs e, RequestPackage package)
        {
            //使用代理分发器时,每个ssid建立一个游服Serssion
            GameSession session       = null;
            var         isProxyClient = !string.IsNullOrEmpty(package.ProxyId);

            if (isProxyClient)
            {
                var proxyGuid = GameSession.SessionId2Guid(package.ProxyId);
                if (!proxyGuid.Equals(Guid.Empty))
                {
                    session = GameSession.Get(proxyGuid);
                    if (session == null)
                    {
                        var switchSession = ServerSsMgr.GetSwitchSession();
                        if (switchSession != null)
                        {
                            session = GameSession.CreateNew(proxyGuid, package.ProxyId, switchSession.KeyCode, package.ProxyIp);
                        }
                        else
                        {
                            TraceLog.WriteError("LobbySocketClient GetSession error, switchSession = null");
                        }
                    }
                }
            }
            else
            {
                session = GameSession.Get(package.SessionId) ?? GameSession.Get(e.Socket.HashCode);
            }
            if (session == null)
            {
                session = GameSession.CreateNew(e.Socket.HashCode, e.Socket, _socketLobby);
            }
            if (!isProxyClient && (!session.Connected || !Equals(session.RemoteAddress, e.Socket.RemoteEndPoint.ToString())))
            {
                GameSession.Recover(session, e.Socket.HashCode, e.Socket, _socketLobby);
            }
            else if (isProxyClient && !Equals(session.RemoteAddress, package.ProxyIp))
            {
                GameSession.RecoverProxy(session, package.ProxyIp);
            }
            return(session);
        }
        private async System.Threading.Tasks.Task ProcessPackage(RequestPackage package, GameSession session)
        {
            if (package == null)
            {
                return;
            }

            try
            {
                ActionGetter actionGetter;
                byte[]       data = new byte[0];
                if (!string.IsNullOrEmpty(package.RouteName))
                {
                    actionGetter = ActionDispatcher.GetActionGetter(package, session);
                    if (CheckRemote(package.RouteName, actionGetter))
                    {
                        MessageStructure response = new MessageStructure();
                        OnCallRemote(package.RouteName, actionGetter, response);
                        data = response.PopBuffer();
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    SocketGameResponse response = new SocketGameResponse();
                    response.WriteErrorCallback += ActionDispatcher.ResponseError;
                    actionGetter = ActionDispatcher.GetActionGetter(package, session);
                    DoAction(actionGetter, response);
                    data = response.ReadByte();
                }
                try
                {
                    if (data.Length > 0)
                    {
                        var switchSession = ServerSsMgr.GetSwitchSession();
                        if (switchSession != null && !string.IsNullOrEmpty(package.ProxyId))
                        {
                            var    paramStr = "ActionId=101&MsgId=0&UserSid=" + package.ProxyId;
                            string sign     = SignUtils.EncodeSign(paramStr, RequestParam.SignKey);
                            paramStr += string.Format("&{0}={1}", "sign", sign);
                            var    postData   = Encoding.UTF8.GetBytes(string.Format("?d={0}", paramStr));
                            byte[] paramBytes = new byte[postData.Length + PackageReader.EnterChar.Length + data.Length];
                            Buffer.BlockCopy(postData, 0, paramBytes, 0, postData.Length);
                            Buffer.BlockCopy(PackageReader.EnterChar, 0, paramBytes, postData.Length, PackageReader.EnterChar.Length);
                            Buffer.BlockCopy(data, 0, paramBytes, postData.Length + PackageReader.EnterChar.Length, data.Length);

                            await switchSession.SendAsync(actionGetter.OpCode, paramBytes, 0, paramBytes.Length, OnSendCompleted);
                        }
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("PostSend error:{0}", ex);
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Task error:{0}", ex);
            }
            finally
            {
                if (session != null)
                {
                    session.ExitSession();
                }
            }
        }