Ejemplo n.º 1
0
 protected override void SuccessCallback(MessageStructure writer, MessageHead head)
 {
     int type = writer.ReadInt();
     if (type == 1)
     {
         int recordCount = writer.ReadInt();
         JsonObject jsonContainer = new JsonObject();
         List<JsonObject> jsonList = new List<JsonObject>();
         for (int i = 0; i < recordCount; i++)
         {
             writer.RecordStart();
             var item = new JsonObject();
             item.Add("NoticeID", writer.ReadString());
             item.Add("Title",  writer.ReadString());
             item.Add("Content", writer.ReadString());
             item.Add("IsBroadcast", writer.ReadInt());
             item.Add("IsTop", writer.ReadInt());
             item.Add("Creater", writer.ReadString());
             item.Add("CreateDate", writer.ReadString());
             item.Add("ExpiryDate", writer.ReadString());
             jsonList.Add(item);
             writer.RecordEnd();
         }
         jsonContainer.Add("total", recordCount);
         jsonContainer.Add("rows", jsonList.ToArray());
         WriteTableJson(jsonContainer);
     }
 }
Ejemplo n.º 2
0
        public override void OnReceiveTimeout(string clientAddress, byte[] receiveData)
        {
            try
            {
                BufferReader reader = new BufferReader(receiveData);
                string paramString = reader.ReadPacketString();
                paramString = HttpUtility.UrlDecode(paramString, Encoding.UTF8);
                int index = paramString.IndexOf("?d=");
                if (index != -1)
                {
                    index += 3;
                    paramString = paramString.Substring(index, paramString.Length - index);
                }
                PacketMessage receivePacket = ParsePacketMessage(clientAddress, paramString, ConnectType.Tcp);
                var recHead = receivePacket.Head;

                int errorCode = LanguageHelper.GetLang().ErrorCode;
                string errorMsg = LanguageHelper.GetLang().RequestTimeout;
                MessageHead head = new MessageHead(recHead.MsgId, recHead.ActionId, "st", errorCode, errorMsg);
                head.HasGzip = true;
                MessageStructure ds = new MessageStructure();
                ds.WriteBuffer(head);
                byte[] data = ds.ReadBuffer();
                OnSendCompleted(clientAddress, data);
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Send to client {0} timeout error:{1}", clientAddress, ex);
            }
        }
Ejemplo n.º 3
0
 protected override bool DecodePacket(MessageStructure reader, MessageHead head)
 {
     responsePack = ProtoBufUtils.Deserialize<Response1010Pack>(netReader.Buffer);
     string responseDataInfo = "";
     responseDataInfo = "request :" + Game.Utils.JsonHelper.prettyJson<Request1010Pack>(req) + "\n";
     responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson<Response1010Pack>(responsePack) + "\n";
     DecodePacketInfo = responseDataInfo;
     int childStepId = getChild(1010);
     System.Console.WriteLine("childStepID:" + childStepId);
     if (childStepId > 0)
     {
         System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();
         /*
           req.UserID = GetParamsData("UserID", req.UserID);
         req.identify = GetParamsData("identify", req.identify);
         req.version = GetParamsData("version", req.version);
         req.the3rdUserID = GetParamsData("the3rdUserID", req.the3rdUserID);
         req.happyPoint = GetParamsData("happyPoint", req.happyPoint);
         req.Rate = GetParamsData("Rate", req.Rate);
         req.index = GetParamsData("index", req.index);
         req.strThe3rdUserID = GetParamsData("strThe3rdUserID", req.strThe3rdUserID);
         req.typeUser = GetParamsData("typeUser", req.typeUser);
          */
         dic.Add("UserID", req.UserID.ToString());
         dic.Add("index", responsePack.index.ToString());
         dic.Add("the3rdUserID", req.the3rdUserID.ToString());
         dic.Add("strThe3rdUserID", req.strThe3rdUserID);
        SetChildStep(childStepId.ToString(), _setting,dic);
     }
     return true;
 }
Ejemplo n.º 4
0
 public virtual void ResponseError(BaseGameResponse response, ActionGetter actionGetter, int errorCode, string errorInfo)
 {
     MessageHead head = new MessageHead(actionGetter.GetMsgId(), actionGetter.GetActionId(), errorCode, errorInfo);
     MessageStructure sb = new MessageStructure();
     sb.WriteBuffer(head);
     response.BinaryWrite(sb.PopBuffer());
 }
Ejemplo n.º 5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="package"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public byte[] ProcessRequest(object package, object param)
        {
            var httpresponse = new SocketGameResponse();
            ActionGetter actionGetter = null;
            try
            {
                httpresponse.WriteErrorCallback += new ScutActionDispatcher().ResponseError;

                RequestPackage p = package as RequestPackage;
                actionGetter = param as ActionGetter;

                if (!string.IsNullOrEmpty(p.RouteName))
                {
                    if (CheckRemote(p.RouteName, actionGetter))
                    {
                        MessageStructure response = new MessageStructure();
                        OnCallRemote(p.RouteName, actionGetter, response);
                        return response.PopBuffer();
                    }
                    httpresponse.WriteError(actionGetter, 10000, "No permission");
                }
                else
                {
                    DoAction(actionGetter, httpresponse);
                }
                return httpresponse.ReadByte();
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Request error:{0}", ex);
                MessageStructure response = new MessageStructure();
                response.WriteBuffer(new MessageHead(0, 10000, "request error"));
                return response.PopBuffer();
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="context"></param>
 public HttpServiceRequest(HttpContext context)
 {
     _buffer = new MessageStructure();
     httpGet = new HttpGet(context.Request);
     response = new HttpGameResponse(context.Response);
     ParamString = httpGet.ParamString;
     SessionId = httpGet.SessionId;
 }
Ejemplo n.º 7
0
 public static byte[] CtorErrMsg(int error, string msg, NameValueCollection requestParam)
 {
     int msgId = Convert.ToInt32(requestParam["msgid"]);
     int actionid = Convert.ToInt32(requestParam["actionid"]);
     var ms = new MessageStructure();
     var head = new MessageHead(msgId, actionid, "st", error, msg);
     ms.WriteBuffer(head);
     return ms.PosGzipBuffer();
 }
Ejemplo n.º 8
0
 protected override bool DecodePacket(MessageStructure reader, MessageHead head)
 {
     responsePack = ProtoBufUtils.Deserialize<Response1003Pack>(netReader.Buffer);
     string responseDataInfo = "";
     responseDataInfo = "request :" + Game.Utils.JsonHelper.prettyJson<Request1003Pack>(req) + "\n";
     responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson<Response1003Pack>(responsePack) + "\n";
     DecodePacketInfo = responseDataInfo;
     return true;
 }
Ejemplo n.º 9
0
 protected override bool DecodePacket(MessageStructure reader, MessageHead head)
 {
     _session.Context.SessionId = reader.ReadString();
     _session.Context.UserId = reader.ReadString().ToInt();
     int UserType = reader.ReadInt();
     string LoginTime = reader.ReadString();
     int GuideID = reader.ReadInt();
     if (GuideID == 1005)
     {
         SetChildStep("1005");
     }
     return true;
 }
Ejemplo n.º 10
0
 protected override bool DecodePacket(MessageStructure reader, MessageHead head)
 {
     responsePack = ProtoBufUtils.Deserialize<ResponsePack>(netReader.Buffer);
      string responseDataInfo = "";
      responseDataInfo  = "request :" + Game.Utils.JsonHelper.prettyJson<Request1000Pack>(req) + "\n";
      responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson<ResponsePack>(responsePack) + "\n";
      DecodePacketInfo = responseDataInfo;
      int childStepId = getChild(1000);
      if(childStepId>0)
      {
         System.Collections.Generic.Dictionary<string,string> dic = new System.Collections.Generic.Dictionary<string,string>();
         dic.Add("UserID",responsePack.UserID.ToString()) ;
         SetChildStep(childStepId.ToString(),_setting,dic);
      }
      return true;
 }
Ejemplo n.º 11
0
        public static string BuildLuaFile(List<ParamInfoModel> paramList, MessageStructure msgReader, string[] keyNames)
        {
            var respParams = paramList.Where(p => p.ParamType == 2).OrderBy(p => p.SortID);
            StringBuilder containerBuilder = new StringBuilder();
            int loopDepth = 0;//循环深度
            List<ParamInfoModel> recordQueue = new List<ParamInfoModel>();
            foreach (var record in respParams)
            {
                string fieldName = record.Field;
                FieldType fieldType = record.FieldType;
                string fieldValue = "";

                if (loopDepth > 0 && fieldType == FieldType.End)
                {
                    loopDepth--;
                    recordQueue.Add(record);
                }
                if (loopDepth == 0 && recordQueue.Count > 0)
                {
                    //处理循环记录
                    ParseRecordEnd(containerBuilder, msgReader, recordQueue, loopDepth, 0, keyNames);
                    recordQueue.Clear();
                }

                if (loopDepth == 0)
                {
                    if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                    {
                        //自动登录
                    }
                    if (fieldType == FieldType.Record)
                    {
                        loopDepth++;
                        recordQueue.Add(record);
                    }
                }
                else if (fieldType != FieldType.End)
                {
                    if (fieldType == FieldType.Record)
                    {
                        loopDepth++;
                    }
                    recordQueue.Add(record);
                }
            }
            return containerBuilder.ToString();
        }
Ejemplo n.º 12
0
        public static string BuildLuaFile(DataTable table, MessageStructure msgReader, string[] keyNames)
        {
            StringBuilder containerBuilder = new StringBuilder();
            int loopDepth = 0;//ѭ�����
            List<DataRow> recordQueue = new List<DataRow>();
            foreach (DataRow record in table.Rows)
            {
                string fieldName = record["Field"].ToString();
                FieldType fieldType = (FieldType)Enum.Parse(typeof(FieldType), record["FieldType"].ToString());
                string fieldValue = "";

                if (loopDepth > 0 && fieldType == FieldType.End)
                {
                    loopDepth--;
                    recordQueue.Add(record);
                }
                if (loopDepth == 0 && recordQueue.Count > 0)
                {
                    //����ѭ����¼
                    ParseRecordEnd(containerBuilder, msgReader, recordQueue, loopDepth, 0, keyNames);
                    recordQueue.Clear();
                }

                if (loopDepth == 0)
                {
                    if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                    {
                        //�Զ���¼
                    }
                    if (fieldType == FieldType.Record)
                    {
                        loopDepth++;
                        recordQueue.Add(record);
                    }
                }
                else if (fieldType != FieldType.End)
                {
                    if (fieldType == FieldType.Record)
                    {
                        loopDepth++;
                    }
                    recordQueue.Add(record);
                }
            }
            return containerBuilder.ToString();
        }
Ejemplo n.º 13
0
        protected override bool DecodePacket(MessageStructure reader, MessageHead head)
        {
            try
            {
                responsePack = ProtoBufUtils.Deserialize<Action3000Response>(netReader.Buffer);
                string responseDataInfo = "";
                responseDataInfo = "request :" + Game.Utils.JsonHelper.prettyJson<Action3000Request>(req) + "\n";
                responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson<Action3000Response>(responsePack) + "\n";
                DecodePacketInfo = responseDataInfo;
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e.Message);
            }

            return true;
        }
Ejemplo n.º 14
0
        public void RequestTimeout(HttpConnection connection)
        {
            var param = connection.Param;
            int msgId = param.Get("MsgId").ToInt();
            int actionId = param.Get("ActionId").ToInt();
            int errorCode = LanguageHelper.GetLang().ErrorCode;
            string errorMsg = LanguageHelper.GetLang().RequestTimeout;
            var head = new MessageHead(msgId, actionId, "st", errorCode, errorMsg);
            head.HasGzip = true;
            var ms = new MessageStructure();
            ms.WriteBuffer(head);
            byte[] data = ms.ReadBuffer();

            string remoteAddress = connection.Context.Request.RemoteEndPoint.Address.ToString();
            string successMsg = string.Format("{0}>>发送超时到{1} {2}字节!",
                                              DateTime.Now.ToString("HH:mm:ss:ms"), remoteAddress, data.Length);
            Console.WriteLine(successMsg);
            OnResponseCompleted(connection, data);
        }
Ejemplo n.º 15
0
 protected override bool DecodePacket(MessageStructure reader, MessageHead head)
 {
     responsePack = ProtoBufUtils.Deserialize<ResponsePack>(netReader.Buffer);
     string responseDataInfo = "";
     responseDataInfo = "request :" + Game.Utils.JsonHelper.prettyJson<Request2000Pack>(req) + "\n";
     responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson<ResponsePack>(responsePack) + "\n";
     DecodePacketInfo = responseDataInfo;
     int childStepId = getChild(2000);
     System.Console.WriteLine("childStepID:"+childStepId);
     if (childStepId > 0)
     {
         System.Collections.Generic.Dictionary<string, string> dic = new System.Collections.Generic.Dictionary<string, string>();
         /*
            req.token = GetParamsData("token",req.token);
                   req.typeUser = GetParamsData("typeUser",req.typeUser);
                   req.version = GetParamsData("version", req.version);
                   req.UserID = GetParamsData("UserID", req.UserID);
          */
         SetChildStep(childStepId.ToString(),_setting,dic);
     }
     return true;
 }
Ejemplo n.º 16
0
        public static bool GetFieldValue(MessageStructure ms, FieldType fieldType, ref string val)
        {
            bool result = false;
            switch (fieldType)
            {
                case FieldType.Int:
                    val = ms.ReadInt().ToString();
                    result = true;
                    break;
                case FieldType.String:
                    val = ms.ReadString();
                    result = true;
                    break;
                case FieldType.Short:
                    val = ms.ReadShort().ToString();
                    result = true;
                    break;
                case FieldType.Byte:
                    val = ms.ReadByte().ToString();
                    result = true;
                    break;
                case FieldType.Long:
                    val = ms.ReadLong().ToString();
                    result = true;
                    break;
                case FieldType.Bool:
                    val = ms.ReadBool().ToString();
                    result = true;
                    break;
                case FieldType.Float:
                    val = ms.ReadFloat().ToString();
                    result = true;
                    break;
                case FieldType.Double:
                    val = ms.ReadDouble().ToString();
                    result = true;
                    break;
                case FieldType.Record:
                    break;
                case FieldType.End:
                    break;
                case FieldType.Head:
                    break;
                default:
                    break;
            }

            return result;
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Call remote method
 /// </summary>
 /// <param name="routePath"></param>
 /// <param name="actionGetter"></param>
 /// <param name="response"></param>
 protected virtual void OnCallRemote(string routePath, ActionGetter actionGetter, MessageStructure response)
 {
     try
     {
         string[] mapList = routePath.Split('.');
         string funcName = "";
         string routeName = routePath;
         if (mapList.Length > 1)
         {
             funcName = mapList[mapList.Length - 1];
             routeName = string.Join("/", mapList, 0, mapList.Length - 1);
         }
         string routeFile = "";
         int actionId = actionGetter.GetActionId();
         MessageHead head = new MessageHead(actionId);
         if (!ScriptEngines.SettupInfo.DisablePython)
         {
             routeFile = string.Format("Remote.{0}", routeName);
             dynamic scope = ScriptEngines.ExecutePython(routeFile);
             if (scope != null)
             {
                 var funcHandle = scope.GetVariable<RemoteHandle>(funcName);
                 if (funcHandle != null)
                 {
                     funcHandle(actionGetter, head, response);
                     response.WriteBuffer(head);
                     return;
                 }
             }
         }
         string typeName = string.Format(GameEnvironment.Setting.RemoteTypeName, routeName);
         routeFile = string.Format("Remote.{0}", routeName);
         var args = new object[] { actionGetter, response };
         var instance = (object)ScriptEngines.Execute(routeFile, typeName, args);
         if (instance is RemoteStruct)
         {
             var target = instance as RemoteStruct;
             target.DoRemote();
         }
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("OnCallRemote error:{0}", ex);
     }
 }
Ejemplo n.º 18
0
 /// <summary>
 /// 
 /// </summary>
 public SocketGameResponse()
 {
     _buffers = new MessageStructure();
 }
Ejemplo n.º 19
0
 //protected override void DoListen()
 //{
 //    this.ServiceProxy.Listen(9001);
 //}
 protected override void OnCallRemote(string route, HttpGet httpGet, MessageHead head, MessageStructure structure)
 {
 }
Ejemplo n.º 20
0
        private static void ParseRecordEnd(StringBuilder itemBuilder, MessageStructure msgReader, List<ParamInfoModel> queue, int depth, int recordNum, string[] keyNames)
        {
            string keyValue = string.Empty;
            string keyName = keyNames.Length > depth ? keyNames[depth] : string.Empty;
            List<LuaConfig> builderList = new List<LuaConfig>();
            int recordCount = 0;
            try
            {
                recordCount = msgReader.ReadInt();
            }
            catch { }
            for (int i = 0; i < recordCount; i++)
            {
                try
                {
                    msgReader.RecordStart();
                    int loopDepth = 0; //循环深度
                    StringBuilder recordBuilder = new StringBuilder();
                    List<ParamInfoModel> recordQueue = new List<ParamInfoModel>();

                    int columnNum = 0;
                    int childNum = 0;

                    #region 遍历列取数据
                    for (int r = 1; r < queue.Count - 1; r++)
                    {
                        var record = queue[r];
                        string fieldName = record.Field;
                        FieldType fieldType = record.FieldType;
                        string fieldValue = "";
                        try
                        {
                            if (loopDepth > 0 && fieldType == FieldType.End)
                            {
                                loopDepth--;
                                recordQueue.Add(record);
                            }
                            if (loopDepth == 0 && recordQueue.Count > 0)
                            {
                                //处理循环记录
                                childNum++;
                                var childBuilder = new StringBuilder();
                                ParseRecordEnd(childBuilder, msgReader, recordQueue, depth + 1, childNum, keyNames);
                                //
                                recordQueue.Clear();
                                //选择输出格式
                                FormatChildToLua(recordBuilder, childBuilder, columnNum);
                            }

                            if (loopDepth == 0)
                            {
                                if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                                {
                                    if (columnNum > 0)
                                    {
                                        recordBuilder.Append(",");
                                    }
                                    if (fieldName.Trim().ToLower() == keyName.Trim().ToLower())
                                    {
                                        keyValue = fieldValue;
                                    }
                                    if (fieldType == FieldType.Byte || fieldType == FieldType.Short || fieldType == FieldType.Int)
                                    {
                                        recordBuilder.AppendFormat("{0}={1}", fieldName, fieldValue);
                                    }
                                    else
                                    {
                                        recordBuilder.AppendFormat("{0}=\"{1}\"", fieldName, fieldValue);
                                    }
                                    columnNum++;
                                }
                                if (fieldType == FieldType.Record)
                                {
                                    loopDepth++;
                                    recordQueue.Add(record);
                                }
                            }
                            else if (fieldType != FieldType.End)
                            {
                                if (fieldType == FieldType.Record)
                                {
                                    loopDepth++;
                                }
                                recordQueue.Add(record);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(string.Format("recordindex:{0},fieldName:{1} error:", i, fieldName), ex);
                        }
                    }

                    #endregion
                    //读取行结束
                    msgReader.RecordEnd();
                    builderList.Add(new LuaConfig { Key = keyValue, Builder = recordBuilder });
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("recordindex:{0}error:", i), ex);
                }
            }

            FormatListToLua(itemBuilder, builderList, keyName, depth, recordNum);
        }
Ejemplo n.º 21
0
 private static void OnNetTcpCallback(object sender, RemoteEventArgs e)
 {
     try
     {
         RemoteService proxy = sender as RemoteService;
         if (proxy == null)
         {
             return;
         }
         try
         {
             using (var ms = new MessageStructure(e.Data))
             {
                 var head = ms.ReadHeadGzip();
                 if (head != null)
                 {
                     var package = proxy.Find(head.MsgId);
                     if (package != null)
                     {
                         package.Message = ms.ReadBuffer();
                         proxy.Remove(head.MsgId);
                         package.OnCallback();
                         return;
                     }
                 }
             }
         }
         catch (Exception)
         { }
         proxy.OnPushedHandle(e);
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("OnNetTcpCallback error:{0}", ex);
     }
 }
Ejemplo n.º 22
0
        private static void ProcessResult(List<ParamInfoModel> paramList, int contractId, StringBuilder respContent, MessageHead msg, MessageStructure msgReader, out string sid, out string uid, out string st)
        {
            sid = "";
            uid = "";
            st = msg.St;
            ResponseHead(contractId, respContent, msg.ErrorCode, msg.ErrorInfo, msg.St);

            //AccountServer Error
            if (msg.ErrorCode < ErrorCode && msg.ErrorCode != 105 && msg.ErrorCode != 106)
            {
                //消息体
                respContent.AppendFormat("<h3>{0}-{1}</h3>", contractId, "返回结果");
                respContent.Append("<table style=\"width:99%; border-color:#f0f0f0\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\">");
                respContent.Append("<tr><td style=\"width:15%;\"><strong>参数</strong></td><td style=\"width:10%;\"><strong>类型</strong></td>");
                respContent.Append("<td style=\"width:75%;\"><strong>参数值</strong></td></tr>");
                int loopDepth = 0;//循环深度
                List<ParamInfoModel> recordQueue = new List<ParamInfoModel>();
                #region 循环体
                foreach (var record in paramList)
                {
                    if (record.FieldType == FieldType.Void)
                    {
                        continue;
                    }
                    string fieldName = record.Field;
                    FieldType fieldType = record.FieldType;
                    string fieldValue = "";
                    try
                    {
                        if (loopDepth > 0 && fieldType == FieldType.End)
                        {
                            loopDepth--;
                            recordQueue.Add(record);
                        }
                        if (loopDepth == 0 && recordQueue.Count > 0)
                        {
                            //处理循环记录
                            ProcessLoopRocord(respContent, recordQueue, msgReader);
                            recordQueue.Clear();
                        }

                        if (loopDepth == 0)
                        {
                            if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                            {
                                //自动登录
                                if (NetHelper.LoginActionId.IndexOf(contractId.ToString(), StringComparison.OrdinalIgnoreCase) != -1)
                                {
                                    if ("SessionID".Equals(fieldName, StringComparison.OrdinalIgnoreCase)) sid = fieldValue;
                                    if ("UserID".Equals(fieldName, StringComparison.OrdinalIgnoreCase)) uid = fieldValue;
                                }
                                respContent.Append("<tr>");
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldName);
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldType);
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldValue);
                                respContent.Append("</tr>");
                            }
                            if (fieldType == FieldType.Record)
                            {
                                loopDepth++;
                                recordQueue.Add(record);
                            }
                        }
                        else if (fieldType != FieldType.End)
                        {
                            if (fieldType == FieldType.Record)
                            {
                                loopDepth++;
                            }
                            recordQueue.Add(record);
                        }
                    }
                    catch (Exception ex)
                    {
                        respContent.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", fieldName, fieldType, ex.ToString());
                    }

                }
                #endregion

                respContent.Append("</table>");

            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// 放入缓冲队列中
 /// </summary>
 /// <param name="value"></param>
 public void PushIntoStack(MessageStructure value)
 {
     PushObjIntoQueue(value);
 }
Ejemplo n.º 24
0
 private void OnCallRemote(string route, HttpGet httpGet, MessageStructure response)
 {
     try
     {
         string[] mapList = route.Split('.');
         string funcName = "";
         string routeName = "";
         if (mapList.Length > 1)
         {
             funcName = mapList[mapList.Length - 1];
             routeName = string.Join("/", mapList, 0, mapList.Length - 1);
         }
         string routeFile = "";
         string typeName = string.Format("Game.Script.Remote.{0}", routeName);
         int actionId = httpGet.ActionId;
         MessageHead head = new MessageHead(actionId);
         if (!ScriptEngines.DisablePython)
         {
             routeFile = string.Format("{0}/Remote/{1}.py", ScriptEngines.PythonDirName, routeName);
             dynamic scope = ScriptEngines.Execute(routeFile, typeName);
             if (scope != null)
             {
                 var funcHandle = scope.GetVariable<RemoteHandle>(funcName);
                 if (funcHandle != null)
                 {
                     funcHandle(httpGet, head, response);
                     response.WriteBuffer(head);
                     return;
                 }
             }
         }
         routeFile = string.Format("{0}/Remote/{1}.cs", ScriptEngines.CSharpDirName, routeName);
         var instance = (object)ScriptEngines.Execute(routeFile, typeName);
         if (instance != null)
         {
             var result = ObjectAccessor.Create(instance, true)[funcName];
         }
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("{0}", ex);
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// 处理循环记录
        /// </summary>
        /// <param name="respContent"></param>
        /// <param name="queue"></param>
        /// <param name="reader"></param>
        private static void ProcessLoopRocord(StringBuilder respContent, List<ParamInfoModel> queue, MessageStructure reader)
        {
            StringBuilder headContent = new StringBuilder();
            StringBuilder builderContent = new StringBuilder();
            int recordCount = 0;
            try
            {
                recordCount = reader.ReadInt();
            }
            catch (Exception ex)
            {
            }
            respContent.Append("<tr>");
            respContent.Append("<td style=\"width:25%;\" align=\"left\">Record(N)</td>");
            respContent.Append("<td style=\"width:20%;\" align=\"left\">Record</td>");
            respContent.AppendFormat("<td style=\"width:50%;\" align=\"left\">{0}</td>", recordCount);
            respContent.Append("</tr>");

            respContent.Append("<tr><td colspan=\"3\" align=\"center\">");
            respContent.Append("<!--子表开始--><table style=\"width:98%; border-color:#999\" border=\"1\" cellpadding=\"2\" cellspacing=\"0\">");
            if (recordCount == 0)
            {
                builderContent.Append("<tr><td align=\"center\">空数据</td></tr>");
            }

            for (int i = 0; i < recordCount; i++)
            {
                try
                {
                    reader.RecordStart();
                    MessageStructure msgReader = reader;
                    int loopDepth = 0; //循环深度
                    List<ParamInfoModel> recordQueue = new List<ParamInfoModel>();

                    headContent.Append("<tr><!--头开始tr-->");
                    builderContent.Append("<tr><!--内容开始tr-->");
                    int columnNum = 0;

                    #region

                    for (int r = 1; r < queue.Count - 1; r++)
                    {
                        var record = queue[r];
                        string fieldName = record.Field;
                        FieldType fieldType = record.FieldType;
                        string fieldValue = "";
                        try
                        {
                            if (loopDepth > 0 && fieldType == FieldType.End)
                            {
                                loopDepth--;
                                recordQueue.Add(record);
                            }
                            if (loopDepth == 0 && recordQueue.Count > 0)
                            {
                                builderContent.Append("</tr><tr>");
                                builderContent.AppendFormat("<td colspan=\"{0}\" align=\"right\">", columnNum);
                                builderContent.Append(
                                    "<!--子表开始--><table style=\"width:95%; border-color:#999\" border=\"1\" cellpadding=\"2\" cellspacing=\"0\">");
                                //处理循环记录
                                ProcessLoopRocord(builderContent, recordQueue, msgReader);

                                builderContent.Append("</table><!--子表结束-->");
                                builderContent.Append("</td>");
                                recordQueue.Clear();
                            }

                            if (loopDepth == 0)
                            {
                                if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                                {
                                    if (i == 0)
                                        headContent.AppendFormat("<td align=\"center\"><strong>{0}</strong>({1})</td>",
                                                                 fieldName, fieldType);
                                    builderContent.AppendFormat("<td align=\"center\">&nbsp;{0}</td>", fieldValue);
                                    columnNum++;
                                }
                                if (fieldType == FieldType.Record)
                                {
                                    loopDepth++;
                                    recordQueue.Add(record);
                                }
                            }
                            else if (fieldType != FieldType.End)
                            {
                                if (fieldType == FieldType.Record)
                                {
                                    loopDepth++;
                                }
                                recordQueue.Add(record);
                            }
                        }
                        catch (Exception ex)
                        {
                            builderContent.AppendFormat("<td align=\"center\">{0}列出错{1}</td>", fieldName, ex.Message);
                        }

                    }

                    #endregion

                    headContent.Append("</tr><!--头结束tr-->");
                    builderContent.Append("</tr><!--内容结束tr-->");
                    //读取行结束
                    reader.RecordEnd();
                }
                catch (Exception ex)
                {
                    builderContent.AppendFormat("<tr><td align=\"left\">{0}行出错{1}</td></tr>", (i + 1), ex.Message);
                }
            }

            respContent.Append(headContent.ToString());
            respContent.Append(builderContent.ToString());
            respContent.Append("</table><!--子表结束-->");
            respContent.Append("</td></tr>");
            respContent.Append("<tr>");
            respContent.Append("<td colspan=\"3\" align=\"left\">End</td>");
            respContent.Append("</tr>");
        }
Ejemplo n.º 26
0
 /// <summary>
 /// 放入缓冲队列中
 /// </summary>
 /// <param name="value"></param>
 public void PushIntoStack(MessageStructure value)
 {
     PushObjIntoQueue(value);
 }
Ejemplo n.º 27
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();
            }
        }
Ejemplo n.º 28
0
        private void ProcessPackage(object state)
        {
            var package = (RequestPackage)state;
            if (package == null) return;

            var session = package.Session;
            try
            {
                byte[] data = new byte[0];
                if (!string.IsNullOrEmpty(package.RouteName))
                {
                    HttpGet httpGet = new HttpGet(package);
                    if (CheckRemote(package.RouteName, httpGet))
                    {
                        MessageStructure response = new MessageStructure();
                        OnCallRemote(package.RouteName, httpGet, response);
                        data = response.PopBuffer();
                    }
                }
                else
                {
                    SocketGameResponse response = new SocketGameResponse();
                    response.WriteErrorCallback += ActionDispatcher.ResponseError;
                    ActionGetter actionGetter = ActionDispatcher.GetActionGetter(package);
                    OnRequested(actionGetter, response);
                    data = response.ReadByte();
                }
                try
                {
                    if (data.Length > 0)
                    {
                        session.SendAsync(data, 0, data.Length);
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("PostSend异常{0}", ex);
                }

            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Task异常{0}", ex);
            }
            finally
            {
                session.ExitSession();
                Interlocked.Decrement(ref runningNum);
            }
        }
Ejemplo n.º 29
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);
     }
 }
Ejemplo n.º 30
0
        private static void ProcessResult(int contractId, int slnId, StringBuilder respContent, MessageHead msg, MessageStructure msgReader, out string sid, out string uid)
        {
            sid = "";
            uid = "";
            //头部消息
            respContent.AppendFormat("<h3>{0}-{1}</h3>", contractId, "基本消息");
            respContent.Append("<table style=\"width:90%; border-color:#999\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\">");
            respContent.Append("<tr><td style=\"width:25%;\"><strong>状态值</strong></td>");
            respContent.Append("<td style=\"width:75%;\"><strong>描述</strong></td></tr>");
            respContent.AppendFormat("<tr><td>{0}</td>", msg.ErrorCode);
            respContent.AppendFormat("<td>{0}&nbsp;</td></tr>", msg.ErrorInfo);
            respContent.Append("</table>");

            if (msg.ErrorCode != ErrorCode)
            {
                var respRecords = GetResponseFields(contractId, slnId);

                //消息体
                respContent.AppendFormat("<h3>{0}-{1}</h3>", contractId, "返回结果");
                respContent.Append("<table style=\"width:90%; border-color:#999\" border=\"1\" cellpadding=\"3\" cellspacing=\"0\">");
                respContent.Append("<tr><td style=\"width:15%;\"><strong>参数</strong></td><td style=\"width:10%;\"><strong>类型</strong></td>");
                respContent.Append("<td style=\"width:75%;\"><strong>参数值</strong></td></tr>");
                int loopDepth = 0;//循环深度
                List<ParamInfoModel> recordQueue = new List<ParamInfoModel>();
                #region 循环体
                foreach (var record in respRecords)
                {
                    string fieldName = record.Field;
                    FieldType fieldType = record.FieldType;
                    string fieldValue = "";
                    try
                    {
                        if (loopDepth > 0 && fieldType == FieldType.End)
                        {
                            loopDepth--;
                            recordQueue.Add(record);
                        }
                        if (loopDepth == 0 && recordQueue.Count > 0)
                        {
                            //处理循环记录
                            ProcessLoopRocord(respContent, recordQueue, msgReader);
                            recordQueue.Clear();
                        }

                        if (loopDepth == 0)
                        {
                            if (NetHelper.GetFieldValue(msgReader, fieldType, ref fieldValue))
                            {
                                //自动登录
                                if ("1004".Equals(contractId))
                                {
                                    if ("SessionID".Equals(fieldName)) sid = fieldValue;
                                    if ("UserID".Equals(fieldName)) uid = fieldValue;
                                }
                                respContent.Append("<tr>");
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldName);
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldType);
                                respContent.AppendFormat("<td>&nbsp;{0}</td>", fieldValue);
                                respContent.Append("</tr>");
                            }
                            if (fieldType == FieldType.Record)
                            {
                                loopDepth++;
                                recordQueue.Add(record);
                            }
                        }
                        else if (fieldType != FieldType.End)
                        {
                            if (fieldType == FieldType.Record)
                            {
                                loopDepth++;
                            }
                            recordQueue.Add(record);
                        }
                    }
                    catch (Exception ex)
                    {
                        respContent.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>", fieldName, fieldType, ex.ToString());
                    }

                }
                #endregion

                respContent.Append("</table>");

            }
        }
Ejemplo n.º 31
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 = (string.IsNullOrEmpty(package.SessionId)
                            ? GameSession.GetSessionByCookie(context.Request)
                            : 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";
                }
                //set cookie
                var cookie = context.Request.Cookies["sid"];
                if (cookie == null)
                {
                    cookie = new Cookie("sid", session.SessionId);
                    cookie.Expires = DateTime.Now.AddMinutes(5);
                    context.Response.SetCookie(cookie);
                }


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

                var clientConnection = new HttpClientConnection
                {
                    Context = context,
                    Session = session,
                    ActionGetter = httpGet,
                    GameResponse = httpresponse
                };
                var section = GetSection();
                clientConnection.TimeoutTimer = new Timer(OnHttpRequestTimeout, clientConnection, section.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);
            }
        }