Beispiel #1
0
 protected override void OnDisconnected(GameSession session)
 {
     var user = session.User as ChatUser;
     if (user != null)
     {
         user.ChatVesion = 0;
     }
     Console.WriteLine("Client {0} is closed.", session.RemoteAddress);
     base.OnDisconnected(session);
 }
Beispiel #2
0
 /// <summary>
 /// Response hearbeat stream.
 /// </summary>
 /// <param name="package"></param>
 /// <param name="session"></param>
 protected void ResponseHearbeat(RequestPackage package, GameSession session)
 {
     try
     {
         MessageStructure response = new MessageStructure();
         response.WriteBuffer(new MessageHead(package.MsgId, package.ActionId, 0));
         var data = response.PopBuffer();
         if (session != null && data.Length > 0)
         {
             session.SendAsync(OpCode.Binary, data, 0, data.Length, OnSendCompleted).Wait();
         }
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("Post Heartbeat error:{0}", ex);
     }
 }
Beispiel #3
0
        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 (session != null && data.Length > 0)
                    {
                        await session.SendAsync(actionGetter.OpCode, data, 0, data.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();
            }
        }
Beispiel #4
0
        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 (session != null && data.Length > 0)
                    {
                        await session.SendAsync(actionGetter.OpCode, data, 0, data.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();
                }
            }
        }
Beispiel #5
0
 /// <summary>
 /// Recover session
 /// </summary>
 /// <param name="session"></param>
 /// <param name="newSessionKey"></param>
 /// <param name="socket"></param>
 /// <param name="sendCallback"></param>
 /// <returns></returns>
 public static void Recover(GameSession session, Guid newSessionKey, ExSocket socket, Action<ExSocket, byte[], int, int> sendCallback)
 {
     var newSession = Get(newSessionKey);
     if (session != null &&
         newSession != null &&
         session != newSession)
     {
         session._exSocket = socket;
         session._sendCallback = sendCallback;
         GameSession temp;
         _globalSession.TryRemove(newSessionKey, out temp);
     }
 }
Beispiel #6
0
 /// <summary>
 /// 心跳包
 /// </summary>
 /// <param name="session"></param>
 protected virtual void OnHeartbeat(GameSession session)
 {
 }
Beispiel #7
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="package"></param>
        /// <param name="session"></param>
        protected virtual void BuildHearbeatPackage(RequestPackage package, GameSession session)
        {

        }
Beispiel #8
0
 protected override void OnDisconnected(GameSession session)
 {
     Console.WriteLine("客户端UserId:[{0}]已与服务器断开", session.EndAddress);
     base.OnDisconnected(session);
 }
Beispiel #9
0
        /// <summary>
        /// Recover session
        /// </summary>
        /// <param name="session"></param>
        /// <param name="newSessionKey"></param>
        /// <param name="socket"></param>
        /// <param name="appServer"></param>
        /// <returns></returns>
        public static void Recover(GameSession session, Guid newSessionKey, ExSocket socket, ISocket appServer) {
            var newSession = Get(newSessionKey);
            if (session != null &&
                newSession != null &&
                session != newSession) {

                try {
                    if (session._exSocket != null) session._exSocket.Close();
                } catch { }
                //modify socket's keycod not found reason
                if (socket != null && appServer != null) {
                    socket.Reset(session.KeyCode);
                    session._exSocket = socket;
                    session.AppServer = appServer;
                }
                GameSession temp;
                if (_globalSession.TryRemove(newSessionKey, out temp)) {
                    Save(session);
                }
            }
        }
Beispiel #10
0
 private static GameSession OnCreate(Guid keyCode, params object[] args) {
     GameSession session;
     if (args.Length == 0) {
         session = new GameSession(keyCode, null);
     } else if (args.Length == 1) {
         session = new GameSession(keyCode, args[0]);
     } else if (args.Length == 2 && args[0] is ExSocket) {
         ExSocket socket = args[0] as ExSocket;
         var appServer = args[1] as ISocket;
         session = new GameSession(keyCode, socket, appServer);
     } else {
         throw new ArgumentOutOfRangeException("param is error");
     }
     _globalSession[keyCode] = session;
     return session;
 }
Beispiel #11
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="session"></param>
 public static void ClearSession(GameSession session) {
     if (session != null) {
         session.Reset();
     }
 }
Beispiel #12
0
 private static void Save(GameSession session) {
     try {
         if (session == null || !session.IsAuthorized) return;
         Expire(session, Timeout);
     } catch (Exception er) {
         TraceLog.WriteError("Save session to redis faild,{0}", er);
     }
 }
Beispiel #13
0
 private static void Expire(GameSession session, int timeout) {
     if (session == null) return;
     var user = MathUtils.ToJson(session.User);
     string sid = session.KeyCode.ToString("N");
     RedisConnectionPool.SetExpire(string.Format("{0}:{1}", sessionRedisKey, sid), user, timeout);
 }
Beispiel #14
0
 protected override void OnDisconnected(GameSession session)
 {
     UnLine((int)session.UserId);
 }
 public override ActionGetter GetActionGetter(RequestPackage package, GameSession session)
 {
     // 可以实现自定的ActionGetter子类
     return new HttpGet(package, session) { OpCode = OpCode.Text };
 }
Beispiel #16
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="package"></param>
 /// <param name="session"></param>
 /// <returns></returns>
 public virtual ActionGetter GetActionGetter(RequestPackage package, GameSession session)
 {
     return new HttpGet(package, session);
 }
Beispiel #17
0
        private static void LoadOfflineData() {
            try {
                IDictionary<string, byte[]> pairs = null;
                RedisConnectionPool.ProcessReadOnly(client => {
                    //client.Add(string.Format("{0}:{1}", sessionRedisKey, sessionId), new GameSession().User, new TimeSpan(Timeout * 1000));
                    var keys = client.SearchKeys(string.Format("{0}:*", sessionRedisKey));
                    if (keys == null || keys.Count == 0) return;
                    pairs = client.GetAll<byte[]>(keys);
                });
                pairs = pairs ?? new Dictionary<string, byte[]>();
                foreach (var pair in pairs) {
                    var arr = pair.Key.Split(new char[] { ':' }, 2);
                    if (arr.Length != 2) continue;
                    Guid sessionId;
                    if (Guid.TryParse(arr[1], out sessionId)) {
                        var user = Encoding.UTF8.GetString(pair.Value).ParseJson<SessionUser>();
                        if (user == null) continue;
                        var session = new GameSession(sessionId, null) { LastActivityTime = user.OnlineDate };
                        _globalSession[sessionId] = session;

                        int userId = user.GetUserId();
                        GameSession oldsession;
                        Guid sid;
                        if (_userHash.TryGetValue(userId, out sid) &&
                            sid != session.KeyCode &&
                            (oldsession = Get(sid)) != null) {
                            //防止先后问题
                            if (session.IsReplaced) {
                                continue;
                            }
                            if (oldsession.IsReplaced || oldsession.LastActivityTime < session.LastActivityTime) {
                                oldsession.Unbind();
                                Expire(oldsession, 0);
                                continue;
                            }
                        }
                        _userHash[userId] = session.KeyCode;
                        session.User = user;
                    }
                }
            } catch (Exception er) {
                TraceLog.WriteError("Load GameSession from redis faild,{0}", er);
            }
        }
 public ActionGetter GetActionGetter(RequestPackage package, GameSession session)
 {
     return new ActionGetter(package, session);
 }
Beispiel #19
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="package"></param>
        /// <param name="session"></param>
        /// <returns></returns>
        protected virtual bool CheckSpecialPackge(RequestPackage package, GameSession session)
        {
            //处理特殊包
            if (package.ActionId == ((int)ActionEnum.Interrupt))
            {
                //Proxy server notifly interrupt connect ops
                OnDisconnected(session);
                if (session != null && (session.ProxySid == Guid.Empty || GameSession.Count > 1))
                {
                    //保留代理服连接
                    session.Close();
                    session.ProxySid = Guid.Empty;
                }
                return true;
            }

            if (package.ActionId == ((int)ActionEnum.Heartbeat))
            {
                if (session != null)
                {
                    // 客户端tcp心跳包
                    session.Refresh();
                    OnHeartbeat(session);
                    BuildHearbeatPackage(package, session);
                    session.ExitSession();
                }
                return true;
            }
            return false;
        }
Beispiel #20
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="session"></param>
 public void Bind(GameSession session)
 {
     if (session != null)
     {
         SessionId = session.SessionId;
         session.ProxyId = ProxyId;
     }
     Session = session;
     ReceiveTime = DateTime.Now;
 }
Beispiel #21
0
 /// <summary>
 /// Raises the disconnected event.
 /// </summary>
 /// <param name="session">Session.</param>
 protected virtual void OnDisconnected(GameSession session)
 {
 }
Beispiel #22
0
 protected override void OnHeartbeat(GameSession session)
 {
     Console.WriteLine("{0}>>Hearbeat package: {1} userid {2} session count {3}", DateTime.Now.ToString("HH:mm:ss"), session.RemoteAddress, session.UserId, GameSession.Count);
     base.OnHeartbeat(session);
 }
Beispiel #23
0
        private bool CheckSpecialPackge(RequestPackage package, GameSession session)
        {
            //处理特殊包
            if (package.ActionId == ((int)ActionEnum.Interrupt))
            {
                //Proxy server notifly interrupt connect ops
                OnDisconnected(session);
                if (session != null && (session.ProxySid == Guid.Empty || GameSession.Count > 1))
                {
                    //保留代理服连接
                    session.Close();
                    session.ProxySid = Guid.Empty;
                }
                return true;
            }

            if (package.ActionId == ((int)ActionEnum.Heartbeat))
            {
                // 客户端tcp心跳包
                session.Refresh();
                OnHeartbeat(session);
                session.ExitSession();
                Interlocked.Decrement(ref runningNum);
                return true;
            }
            return false;
        }
Beispiel #24
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="session"></param>
 public void Bind(GameSession session)
 {
     if (session != null)
     {
         SessionId = session.SessionId;
         session.ProxyId = ProxyId;
         //push not refresh
         if (MsgId > 0) session.Refresh();
     }
     //Session = session;
     ReceiveTime = DateTime.Now;
 }
Beispiel #25
0
 private static GameSession OnCreate(Guid keyCode, params object[] args)
 {
     GameSession session;
     if (args.Length == 1)
     {
         session = new GameSession(keyCode, args[0]);
     }
     else if (args.Length == 2 && args[0] is ExSocket)
     {
         ExSocket socket = args[0] as ExSocket;
         var sendCallback = args[1] as Action<ExSocket, byte[], int, int>;
         session = new GameSession(keyCode, socket, sendCallback);
     }
     else
     {
         throw new ArgumentOutOfRangeException("param is error");
     }
     _globalSession[keyCode] = session;
     return session;
 }
Beispiel #26
0
        private static void LoadUnLineData()
        {
            try
            {
                IDictionary <string, byte[]> pairs = null;
                RedisConnectionPool.ProcessReadOnly(client =>
                {
                    //client.Add(string.Format("{0}:{1}", sessionRedisKey, sessionId), new GameSession().User, new TimeSpan(Timeout * 1000));
                    var keys = client.SearchKeys(string.Format("{0}:*", sessionRedisKey));
                    if (keys == null || keys.Count == 0)
                    {
                        return;
                    }
                    pairs = client.GetAll <byte[]>(keys);
                });
                pairs = pairs ?? new Dictionary <string, byte[]>();
                foreach (var pair in pairs)
                {
                    var arr = pair.Key.Split(new char[] { ':' }, 2);
                    if (arr.Length != 2)
                    {
                        continue;
                    }
                    Guid sessionId;
                    if (Guid.TryParse(arr[1], out sessionId))
                    {
                        var user = Encoding.UTF8.GetString(pair.Value).ParseJson <SessionUser>();
                        if (user == null)
                        {
                            continue;
                        }
                        var session = new GameSession(sessionId, null)
                        {
                            LastActivityTime = user.OnlineDate
                        };
                        _globalSession[sessionId] = session;

                        int         userId = user.GetUserId();
                        GameSession oldsession;
                        Guid        sid;
                        if (_userHash.TryGetValue(userId, out sid) &&
                            sid != session.KeyCode &&
                            (oldsession = Get(sid)) != null)
                        {
                            //防止先后问题
                            if (session.IsReplaced)
                            {
                                continue;
                            }

                            if (oldsession.IsReplaced || oldsession.LastActivityTime < session.LastActivityTime)
                            {
                                oldsession.UnBind();
                                Expire(oldsession, 0);
                                continue;
                            }
                        }
                        _userHash[userId] = session.KeyCode;
                        session.User      = user;
                    }
                }
            }
            catch (Exception er)
            {
                TraceLog.WriteError("Load GameSession from redis faild,{0}", er);
            }
        }