Exemple #1
0
        private GameSession GetSession(ConnectionEventArgs e, RequestPackage package)
        {
            //使用代理分发器时,每个ssid建立一个游服Serssion
            GameSession session;

            if (package.ProxySid != Guid.Empty)
            {
                session = GameSession.Get(package.ProxySid) ??
                          (package.IsProxyRequest
                              ? GameSession.Get(e.Socket.HashCode)
                              : GameSession.CreateNew(package.ProxySid, e.Socket, socketListener));
                if (session != null)
                {
                    session.ProxySid = package.ProxySid;
                }
            }
            else
            {
                session = GameSession.Get(package.SessionId) ?? GameSession.Get(e.Socket.HashCode);
            }
            if (session == null)
            {
                session = GameSession.CreateNew(package.ProxySid, e.Socket, socketListener);
            }
            if ((!session.Connected || !Equals(session.RemoteAddress, e.Socket.RemoteEndPoint.ToString())))
            {
                GameSession.Recover(session, e.Socket.HashCode, e.Socket, socketListener);
            }
            return(session);
        }
Exemple #2
0
        /// <summary>
        /// 构造函数
        /// </summary>
        public HttpGet(HttpRequest request)
            : base(null, null)
        {
            _paramString = request["d"] ?? "";
            InitData(_paramString);
            //http
            string sessionId = "";

            if (_param.ContainsKey(ParamSid))
            {
                sessionId = _param[ParamSid];
            }
            if (string.IsNullOrEmpty(sessionId))
            {
                sessionId = request[ParamSid];
            }
            _session = GameSession.Get(sessionId) ?? GameSession.CreateNew(Guid.NewGuid(), request);

            //set cookie
            var cookie = request.Cookies.Get(ParamSid);

            if (cookie == null && HttpContext.Current != null)
            {
                cookie         = new HttpCookie(ParamSid, SessionId);
                cookie.Expires = DateTime.Now.AddMinutes(5);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
Exemple #3
0
        private GameSession GetSession(ConnectionEventArgs e, RequestPackage package)
        {
            //使用代理分发器时,每个ssid建立一个游服Serssion
            GameSession session;

            if (package.ProxySid != Guid.Empty)
            {
                session = GameSession.Get(package.ProxySid) ??
                          (package.IsProxyRequest
                              ? GameSession.Get(e.Socket.HashCode)
                              : GameSession.CreateNew(package.ProxySid, e.Socket, socketLintener.PostSend));
                if (session != null)
                {
                    session.ProxySid = package.ProxySid;
                }
            }
            else
            {
                session = GameSession.Get(package.SessionId) ?? GameSession.Get(e.Socket.HashCode);
            }
            if (session != null && !session.Connected)
            {
                GameSession.Recover(session, e.Socket.HashCode, e.Socket, socketLintener.PostSend);
            }
            return(session);
        }
Exemple #4
0
 private void socketLintener_OnConnectCompleted(object sender, ConnectionEventArgs e)
 {
     try
     {
         GameSession.CreateNew(e.Socket.HashCode, e.Socket, socketLintener.PostSend);
         OnConnectCompleted(sender, e);
     }
     catch (Exception err)
     {
         TraceLog.WriteError("ConnectCompleted error:{0}", err);
     }
 }
Exemple #5
0
 /// <summary>
 /// 构造函数
 /// </summary>
 public HttpGet(HttpRequest request)
 {
     _paramString = request["d"] ?? "";
     InitData(_paramString);
     //http
     if (_param.ContainsKey("sid"))
     {
         SessionId = _param["sid"];
     }
     _session = GameSession.Get(SessionId)
                ?? GameSession.CreateNew(Guid.NewGuid(), request);
 }
Exemple #6
0
 private void socketLintener_OnConnectCompleted(ISocket sender, ConnectionEventArgs e)
 {
     try
     {
         var session = GameSession.CreateNew(e.Socket.HashCode, e.Socket, socketListener);
         session.HeartbeatTimeoutHandle += OnHeartbeatTimeout;
         OnConnectCompleted(sender, e);
     }
     catch (Exception err)
     {
         TraceLog.WriteError("ConnectCompleted error:{0}", err);
     }
 }
Exemple #7
0
        private static GameSession GetSession(System.Web.HttpContext context, RequestPackage package)
        {
            GameSession session;

            if (package.ProxySid != Guid.Empty)
            {
                session          = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request);
                session.ProxySid = package.ProxySid;
            }
            else
            {
                session = GameSession.Get(package.SessionId) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request);
            }
            return(session);
        }
Exemple #8
0
        public async Task <IHttpResponseAction> Execute(IHttpRequestContext context)
        {
            int            statusCode;
            RequestPackage package;
            var            actionDispatcher = GameEnvironment.Setting.ActionDispatcher;

            if (!actionDispatcher.TryDecodePackage(context.Request, out package, out statusCode))
            {
                return(new ByteResponse(statusCode, statusCode == 200 ? "OK" : "FAIL", new byte[0]));
            }

            GameSession session;

            if (package.ProxySid != Guid.Empty)
            {
                session          = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request);
                session.ProxySid = package.ProxySid;
            }
            else
            {
                session = GameSession.Get(package.SessionId) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request);
            }
            package.Bind(session);

            ActionGetter httpGet = actionDispatcher.GetActionGetter(package, session);

            if (package.IsUrlParam)
            {
                httpGet["UserHostAddress"] = session.RemoteAddress;
                httpGet["ssid"]            = session.KeyCode.ToString("N");
                httpGet["http"]            = "1";
            }

            var result = await System.Threading.Tasks.Task.Run <byte[]>(() =>
            {
                try
                {
                    return(ScriptEngines.GetCurrentMainScript().ProcessRequest(package, httpGet));
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("Excute mainclass error:{0}", ex);
                    return(new byte[0]);
                }
            });

            return(new ByteResponse(statusCode, "OK", result));
        }
Exemple #9
0
        /// <summary>
        /// 构造函数
        /// </summary>
        public HttpGet(HttpRequest request)
            : base(null, null)
        {
            _paramString = request["d"] ?? "";
            InitData(_paramString);
            //http
            string sessionId = "";

            if (_param.ContainsKey("sid"))
            {
                sessionId = _param["sid"];
            }
            if (string.IsNullOrEmpty(sessionId))
            {
                sessionId = request["sid"];
            }
            _session = GameSession.Get(sessionId) ?? GameSession.CreateNew(Guid.NewGuid(), request);
        }
        private static GameSession GetSession(System.Web.HttpContext context, RequestPackage package)
        {
            GameSession session;

            if (package.ProxySid != Guid.Empty)
            {
                session          = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request);
                session.ProxySid = package.ProxySid;
            }
            else
            {
                session = (string.IsNullOrEmpty(package.SessionId)
                        ? GameSession.GetSessionByCookie(context.Request)
                        : GameSession.Get(package.SessionId))
                          ?? GameSession.CreateNew(Guid.NewGuid(), context.Request);
            }
            session.InitHttp(context.Request);
            return(session);
        }
Exemple #11
0
        private void OnHttpRequest(IAsyncResult result)
        {
            try
            {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                listener.BeginGetContext(OnHttpRequest, listener);

                RequestPackage package;
                if (!ActionDispatcher.TryDecodePackage(context, out package))
                {
                    return;
                }

                GameSession session;
                if (package.ProxySid != Guid.Empty)
                {
                    session          = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request);
                    session.ProxySid = package.ProxySid;
                }
                else
                {
                    session = GameSession.Get(package.SessionId) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request);
                }
                package.Bind(session);

                ActionGetter httpGet = ActionDispatcher.GetActionGetter(package);
                if (package.IsUrlParam)
                {
                    httpGet["UserHostAddress"] = session.EndAddress;
                    httpGet["ssid"]            = session.KeyCode.ToString("N");
                    httpGet["http"]            = "1";
                }

                var httpresponse = new SocketGameResponse();
                httpresponse.WriteErrorCallback += new ScutActionDispatcher().ResponseError;

                var clientConnection = new HttpClientConnection
                {
                    Context      = context,
                    Session      = session,
                    ActionGetter = httpGet,
                    GameResponse = httpresponse
                };
                clientConnection.TimeoutTimer = new Timer(OnHttpRequestTimeout, clientConnection, httpRequestTimeout, Timeout.Infinite);
                byte[] respData = new byte[0];
                if (!string.IsNullOrEmpty(package.RouteName))
                {
                    if (CheckRemote(package.RouteName, httpGet))
                    {
                        MessageStructure response = new MessageStructure();
                        OnCallRemote(package.RouteName, httpGet, response);
                        respData = response.PopBuffer();
                    }
                }
                else
                {
                    DoAction(httpGet, httpresponse);
                    respData = httpresponse.ReadByte();
                }
                OnHttpResponse(clientConnection, respData, 0, respData.Length);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("OnHttpRequest error:{0}", ex);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <IHttpResponseAction> Execute(IHttpRequestContext context)
        {
            int            statusCode;
            RequestPackage package;
            var            actionDispatcher = GameEnvironment.Setting.ActionDispatcher;

            if (!actionDispatcher.TryDecodePackage(context.Request, out package, out statusCode))
            {
                return(new ByteResponse(statusCode, statusCode == 200 ? "OK" : "FAIL", new byte[0]));
            }

            GameSession session;

            if (package.ProxySid != Guid.Empty)
            {
                session          = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request);
                session.ProxySid = package.ProxySid;
            }
            else
            {
                session = (string.IsNullOrEmpty(package.SessionId)
                        ? GameSession.GetSessionByCookie(context.Request)
                        : GameSession.Get(package.SessionId))
                          ?? GameSession.CreateNew(Guid.NewGuid(), context.Request);
            }
            session.InitHttp(context.Request);
            session.RemoteAddress = context.UserHostAddress;
            package.Bind(session);

            ActionGetter httpGet = actionDispatcher.GetActionGetter(package, session);

            if (package.IsUrlParam)
            {
                httpGet["UserHostAddress"] = session.RemoteAddress;
                httpGet["ssid"]            = session.KeyCode.ToString("N");
                httpGet["http"]            = "1";
            }

            var result = await System.Threading.Tasks.Task.Run <byte[]>(() =>
            {
                try
                {
                    return(ScriptEngines.GetCurrentMainScript().ProcessRequest(package, httpGet));
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("Excute mainclass error:{0}", ex);
                    return(new byte[0]);
                }
            });

            string sessionId = session.SessionId;
            var    response  = new ByteResponse(statusCode, "OK", result, session.UserId.ToString())
            {
                RequestParams = package.OriginalParam
            };

            response.CookieHandle += ctx =>
            {
                var cookie = ctx.Request.Cookies["sid"];
                if (cookie == null)
                {
                    cookie         = new Cookie("sid", sessionId);
                    cookie.Expires = DateTime.Now.AddMinutes(5);
                    ctx.Response.SetCookie(cookie);
                }
            };
            return(response);
        }
Exemple #13
0
        private void OnHttpRequest(IAsyncResult result)
        {
            try
            {
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                listener.BeginGetContext(OnHttpRequest, listener);
                HttpListenerRequest  request  = context.Request;
                HttpListenerResponse response = context.Response;
                string      sid = request.QueryString["sid"];
                GameSession session;
                if (string.IsNullOrEmpty(sid))
                {
                    session = GameSession.CreateNew(Guid.NewGuid(), request);
                }
                else
                {
                    session = GameSession.Get(sid) ?? GameSession.CreateNew(Guid.NewGuid(), request);
                }

                string data = "";
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    if (string.Compare(request.HttpMethod, "get", true) == 0)
                    {
                        data = request.RawUrl.Substring(8);
                        data = HttpUtility.UrlDecode(data);
                    }
                }
                else
                {
                    data = request.QueryString["d"];
                }

                if (string.IsNullOrEmpty(data))
                {
                    using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
                    {
                        data = reader.ReadToEnd();
                        data = HttpUtility.ParseQueryString(data)["d"];
                    }
                }

                int statuscode = 0;
                Dictionary <string, string> param = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
                if (data != null)
                {
                    var nvc = HttpUtility.ParseQueryString(data);
                    foreach (var key in nvc.AllKeys)
                    {
                        param[key] = nvc[key];
                    }
                }
                statuscode = CheckHttpParam(param);

                if (statuscode != (int)HttpStatusCode.OK)
                {
                    response.StatusCode = statuscode;
                    response.Close();
                    return;
                }

                var httpresponse = new SocketGameResponse();
                httpresponse.WriteErrorCallback += new ActionDispatcher().ResponseError;

                HttpGet httpGet = new HttpGet(new RequestPackage()
                {
                    UrlParam = data, Session = session
                });
                httpGet["UserHostAddress"] = session.EndAddress;
                httpGet["ssid"]            = session.KeyCode.ToString("N");
                httpGet["http"]            = "1";

                var clientConnection = new HttpClientConnection {
                    Context      = context,
                    Session      = session,
                    ActionGetter = httpGet,
                    GameResponse = httpresponse
                };
                clientConnection.TimeoutTimer = new Timer(OnHttpRequestTimeout, clientConnection, httpRequestTimeout, Timeout.Infinite);


                OnRequested(httpGet, httpresponse);
                byte[] respData = httpresponse.ReadByte();
                OnHttpResponse(clientConnection, respData, 0, respData.Length);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("OnHttpRequest error:{0}", ex);
            }
        }
Exemple #14
0
        private void socketLintener_DataReceived(object sender, ConnectionEventArgs e)
        {
            try
            {
                Interlocked.Increment(ref receiveNum);
                OnReceivedBefore(e);
                //if (isInStopping) return;
                Dictionary <string, string> param = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);
                string paramStr  = Encoding.ASCII.GetString(e.Data);
                int    index     = paramStr.IndexOf("?d=");
                string routeName = string.Empty;
                if (index != -1)
                {
                    if (paramStr.StartsWith("route:", StringComparison.CurrentCultureIgnoreCase))
                    {
                        routeName = paramStr.Substring(6, index - 6);
                    }
                    paramStr = paramStr.Substring(index, paramStr.Length - index);
                    paramStr = HttpUtility.ParseQueryString(paramStr)["d"];
                }

                var nvc = HttpUtility.ParseQueryString(paramStr);
                foreach (var key in nvc.AllKeys)
                {
                    param[key] = nvc[key];
                }
                if (param.ContainsKey("route"))
                {
                    routeName = param["route"];
                }
                //if (!param.ContainsKey("ssid")) { Interlocked.Increment(ref errorDropNum); return; }
                if (!param.ContainsKey("actionid"))
                {
                    Interlocked.Increment(ref errorDropNum); return;
                }
                if (!param.ContainsKey("msgid"))
                {
                    Interlocked.Increment(ref errorDropNum); return;
                }

                //sessionId of proxy server
                Guid proxySid;
                if (!param.ContainsKey("ssid") || !Guid.TryParse(param["ssid"], out proxySid))
                {
                    proxySid = Guid.Empty;
                }
                int actionid;
                if (!int.TryParse(param["actionid"], out actionid))
                {
                    Interlocked.Increment(ref errorDropNum); return;
                }
                int msgid;
                if (!int.TryParse(param["msgid"], out msgid))
                {
                    Interlocked.Increment(ref errorDropNum); return;
                }
                bool   isproxy   = param.ContainsKey("isproxy");//proxy server send
                string sessionId = param.ContainsKey("sid") ? param["sid"] : "";

                //使用代理分发器时,每个ssid建立一个游服Serssion
                GameSession session;
                if (proxySid != Guid.Empty)
                {
                    session = GameSession.Get(proxySid) ??
                              (isproxy
                                ? GameSession.Get(e.Socket.HashCode)
                                : GameSession.CreateNew(proxySid, e.Socket, socketLintener.PostSend));
                    session.ProxySid = proxySid;
                }
                else
                {
                    session = GameSession.Get(e.Socket.HashCode);
                }
                if (session != null && !session.Connected)
                {
                    GameSession.Recover(session, e.Socket.HashCode, e.Socket, socketLintener.PostSend);
                }
                if (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;
                }


                requestQueue.Enqueue(new RequestPackage
                {
                    Route       = routeName,
                    ActionId    = actionid,
                    Param       = paramStr,
                    Session     = session,
                    ReceiveTime = DateTime.Now
                });
                singal.Set();
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Received to Host:{0} error:{1}", e.Socket.RemoteEndPoint, ex);
            }
        }