Exemplo n.º 1
0
        /// <summary>
        ///客户端服务程序(连接云服务器)
        /// </summary>
        private static void ApiSrvThread(object ob)
        {
            ServerXml oServerXml  = ob as ServerXml;
            int       iLastSecond = -1;
            DateTime  oNow;
            //string strApiUrl = "http://127.0.0.1:7788/";
            string strApiUrl = "http://127.0.0.1:" + oServerXml.API_Port + "/";
            RemoteCtrlInfoQueryServices service = new RemoteCtrlInfoQueryServices();
            WebServiceHost _serviceHost         = new WebServiceHost(service, new Uri(strApiUrl));

            //或者第二种方法:WebServiceHost _serviceHost = new WebServiceHost(typeof(PersonInfoQueryServices), new Uri("http://127.0.0.1:7788/"));
            try
            {
                //如果这里报错,IDE必须以管理员方式运行
                _serviceHost.Open();
                //LogHelper.WriteLog(string.Format("Socket {0}:{1}启动失败,请检查权限或端口是否被占用!", config.Ip, config.Port));
                LogHelp.Info("API 服务启动成功" + strApiUrl);
                while (m_ClientSvrthread.IsAlive)
                {
                    oNow = DateTime.Now;
                    //秒任务
                    SecondTask(ref iLastSecond, oNow);
                    Thread.Sleep(100);
                }
                _serviceHost.Close();
            }
            catch (System.Exception ex)
            {
                //LogHelper.WriteLog(string.Format("Socket {0}:{1}启动失败,请检查权限或端口是否被占用!", config.Ip, config.Port));
                LogHelp.Info(ex.Message);
                LogHelp.Info("如果提示:HTTP 无法注册 " + strApiUrl + ",尝试以管理员运行程雪");
            }
        }
Exemplo n.º 2
0
 public ActionResult Index()
 {
     LogHelp.Debug("Debug");
     LogHelp.Info("Info");
     LogHelp.Error("Error");
     return(View());
 }
Exemplo n.º 3
0
        private static void Main()
        {
            LogHelp.Init(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogConfig.log4net"));
            LogHelp.TestLog();
            log = LogHelp.GetLogger(typeof(Program));

            Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));

            log.Info("Hello Server!");

            Server = new GameServer(128, 8192);
            Server.Init(2048);
            // 反序列化消息
            Server.MessageHandler.SetDeserializeFunc((bytes, guid) =>
            {
                var protoId = BitConverter.ToInt32(bytes);
                return(new ExtSocket {
                    Protocol = ProtocolParser.Instance.GetParser(protoId).ParseFrom(bytes) as ProtocolBufBase, Guid = guid, ESocketType = ESocketType.ESocketReceive
                });
            });
            // 序列化消息
            Server.MessageHandler.SetSerializeFunc((protocol) =>
            {
                return((protocol as ProtocolBufBase).Serialize());
            });
            Server.Start("127.0.0.1", 11000);

            // 主循环
            stopwatch.Start();
            var t1 = stopwatch.ElapsedMilliseconds;
            var t2 = stopwatch.ElapsedMilliseconds;

            TimerManager.Init();
            SDungeon.Instance.Init();
            while (true)
            {
                t1 = stopwatch.ElapsedMilliseconds;

                // 消息处理
                Server.ProcessMessage();
                // 定时器处理
                TimerManager.Update(stopwatch.ElapsedMilliseconds);

                SDungeon.Instance.Update();
                SNotify.Instance.Update();
                SMove.Instance.Update();

                t2 = stopwatch.ElapsedMilliseconds;
                var t = (int)(t2 - t1);
                System.Threading.Thread.Sleep(t < 30 ? 30 - t : 1);
                if (t > 200)
                {
                    log.Warn($"Performance warning! One tick cost {t} ms!");
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 把请求的报文和返回的报文保存到日志中
        /// 用法:
        /// Gloab中 GlobalConfiguration.Configuration.MessageHandlers.Add(new CustomMessageHandler());
        /// </summary>
        /// <param name="request">请求信息</param>
        /// <param name="cancellationToken">取消操作的标记</param>
        /// <returns></returns>
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string id = Guid.NewGuid().ToString("N");
            var    sc = Stopwatch.StartNew();

            //请求
            if (request.Content != null)
            {
                var    sb = new StringBuilder();
                string ip = GetClientIp(request);
                sb.AppendLine(string.Format("请求IP:{0}", ip));
                string method = request.Method.Method;
                if (method.ToLower().Equals("post"))
                {
                    sb.AppendLine(string.Format("请求Id:{0}", id));
                    sb.AppendLine(string.Format("请求Url-{0}", request.RequestUri.ToString()));
                    sb.AppendLine(string.Format("请求Content:{0}", request.Content.ReadAsStringAsync().Result));
                }
                else
                {
                    sb.AppendLine(string.Format("请求Url-{0}:{1}", id, request.RequestUri.ToString()));
                }
                _logger.Info(sb.ToString());
            }

            return(base.SendAsync(request, cancellationToken).ContinueWith(
                       task =>
            {
                string response = task.Result.Content.ReadAsStringAsync().Result;

                var sb = new StringBuilder();
                sb.AppendLine("响应Id:" + id);
                sb.AppendLine("响应时间:" + sc.ElapsedMilliseconds);
                sb.AppendLine("响应报文:" + response);

                //_logger.Info(string.Format("响应Content-{2}:{0}{1}——————————————————————————————", response, Environment.NewLine, id));
                _logger.Info(sb.ToString());
                return task.Result;
            }, cancellationToken));
        }
Exemplo n.º 5
0
        /// <summary>
        /// 启动服务器端服务
        /// </summary>
        /// <param name="oServerXml">界面的xml参数</param>
        public void ServerSvrStart(ServerXml oServerXml)
        {
            var config = new SuperSocket.SocketBase.Config.ServerConfig()
            {
                Name                     = "SSServer",
                ServerTypeName           = "SServer",
                ClearIdleSession         = true, //60秒执行一次清理90秒没数据传送的连接
                ClearIdleSessionInterval = 60,
                IdleSessionTimeOut       = 90,
                MaxRequestLength         = 4096, //最大包长度
                Ip   = "Any",
                Port = Convert.ToInt32(oServerXml.Port),
                MaxConnectionNumber = 100000,
            };

            //var app = new MyServer();
            //LogHelper.SetOnLog(new LogHelper.LogEvent((m) =>
            //{
            //    txtAll.Text = string.Join(" ", m, "\r\n");
            //    txtAll.Select(txtAll.TextLength, 0);
            //    txtAll.ScrollToCaret();
            //}));
            mMyServer.Setup(config);
            if (!mMyServer.Start())
            {
                //LogHelper.WriteLog(string.Format("Socket {0}:{1}启动失败,请检查权限或端口是否被占用!", config.Ip, config.Port));
                LogHelp.Info(string.Format("Socket {0}:{1}启动失败,请检查权限或端口是否被占用!", config.Ip, config.Port));
            }


            //启动个线程
            m_MonitorDBThreadID = new Thread(MonitorDBThread);
            //主线程退出,此线程立刻退出
            m_MonitorDBThreadID.IsBackground = true;
            m_MonitorDBThreadID.Start();

            LogHelp.Info("监听数据库线程启动完成!");
        }
Exemplo n.º 6
0
        /// <summary>
        /// 监听数据库的线程
        /// </summary>
        private static void MonitorDBThread()
        {
            while (m_MonitorDBThreadID.IsAlive)
            {
                Thread.Sleep(1000);
                if (DateTime.Now.Minute % 5 == 0)
                {
                    //5分钟检查一次数据库
                    nics_regulator_historyBLL     oNics_regulator_historyBLL = new nics_regulator_historyBLL();
                    List <nics_regulator_history> lst = oNics_regulator_historyBLL.GetWebNeedOperate();
                    foreach (var oNics_regulator_history in lst)
                    {
                        oNics_regulator_historyBLL.CenterSetWebCmd(oNics_regulator_history);

                        lock (NICSServerProgram.mMyServer)
                        {
                            var allSessions = NICSServerProgram.mMyServer.GetAllSessions();
                            int iCounter    = allSessions.Count(p => p.ClientID == oNics_regulator_history.client_id.ToString());
                            if (iCounter == 0)
                            {
                                //什么都不需要做
                            }
                            else
                            {
                                //关闭老连接
                                List <MySession> lstMySession = allSessions.Where(p => p.ClientID == oNics_regulator_history.client_id.ToString()).ToList();
                                foreach (var oMySession in lstMySession)
                                {
                                    oMySession.Close();
                                    LogHelp.Info("控制器配置信息更新断开客户端ID:" + oMySession.ClientID + "       IP:" + oMySession.RemoteEndPoint);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        public override void ExecuteCommand(MySession session, MyRequestInfo requestInfo)
        {
            if (requestInfo.IsCorrectPkg)
            {
                if ((requestInfo.BodyKey == "LOGIN") || (requestInfo.BodyKey == "LOGIN2"))
                {
                    string strClientID = requestInfo.ClientID;

                    if (requestInfo.BodyKey == "LOGIN2")
                    {
                        //根据验证码查询客户端ID,并返回给客户端
                        nics_clientBLL oNics_clientBLL = new nics_clientBLL();
                        strClientID = oNics_clientBLL.GetClientID(strClientID);
                    }

                    //根据站点号,查询相应的配置信息
                    nics_regulatorBLL      oNics_regulatorBLL = new nics_regulatorBLL();
                    List <ControllersInfo> lst     = oNics_regulatorBLL.GetModelsByClientID(strClientID);
                    string         strJson         = JsonConvert.SerializeObject(lst);
                    ControllerInfo oControllerInfo = new ControllerInfo(strClientID, strJson);

                    lock (NICSServerProgram.mMyServer)
                    {
                        var allSessions = NICSServerProgram.mMyServer.GetAllSessions();
                        int iCounter    = allSessions.Count(p => p.ClientID == strClientID);
                        if (iCounter == 0)
                        {
                            session.ClientID = strClientID;
                            string strString = oControllerInfo.GetPkg();
                            session.Send(strString);
                        }
                        else
                        {
                            //关闭老连接
                            List <MySession> lstMySession = allSessions.Where(p => p.ClientID == strClientID).ToList();
                            foreach (var o in lstMySession)
                            {
                                if (o.SessionID != session.SessionID)
                                {
                                    LogHelp.Info("断开的客户端ID:" + o.ClientID + "       IP:" + o.RemoteEndPoint);
                                    o.Close();
                                }
                            }
                            //给新的发送注册信息
                            session.ClientID = strClientID;
                            string strString = oControllerInfo.GetPkg();
                            session.Send(strString);

                            LogHelp.Info("重复的客户端ID:" + strClientID + "       IP:" + session.RemoteEndPoint);
                        }
                    }
                }
                else if (requestInfo.BodyKey == "BYPASS")
                {
                    NICSServerProgram.TellAPIByRsp(requestInfo.OnePkg);
                }
                else
                {
                }
            }


            //session.Send(requestInfo.Parameters.Select(p => int.Parse(p)).Sum().ToString());
        }
Exemplo n.º 8
0
 void MyServer_SessionClosed(MySession session, CloseReason value)
 {
     LogHelp.Info(string.Format("Socket {0}断开连接!原因:{1}", session.RemoteEndPoint, value.ToString()));
 }
Exemplo n.º 9
0
 void MyServer_NewSessionConnected(MySession session)
 {
     //连接成功
     LogHelp.Info(string.Format("Socket {0}连接成功!", session.RemoteEndPoint));
 }
Exemplo n.º 10
0
 protected override void OnStarted()
 {
     //启动成功
     //LogHelper.WriteLog(string.Format("Socket启动成功:{0}:{1}", this.Config.Ip, this.Config.Port));
     LogHelp.Info(string.Format("Socket启动成功:{0}:{1}", this.Config.Ip, this.Config.Port));
 }
Exemplo n.º 11
0
 protected override void HandleException(Exception e)
 {
     //这里先不要发送给客户端,直接在屏幕上显示出来
     //this.Send("Application error: {0}", e.Message);
     LogHelp.Info("Application error:" + e.Message);
 }