Exemplo n.º 1
0
 private void CheckConnectorSend(WatchObject wo)
 {
     if (wo.connected && wo.connector.State == EConnectorState.ExpectConnected && !wo.connector.IsSending)
     {
         wo.connector.Send();
     }
 }
Exemplo n.º 2
0
 private void CheckHeartBeat(WatchObject wo)
 {
     if (!wo.sendHeartBeat)
     {
         return;
     }
     // 连接器状态是连接上的,也没有处于重连过程中,那么可以检查心跳和发送心跳
     if (wo.connected && !wo.reconnect && wo.connector.State == EConnectorState.ExpectConnected)
     {
         // 只有发送过心跳了,才需要检查心跳反馈
         if (wo.lastHeartBeatTime > 0f)
         {
             if (wo.lastHeartBeatReturnTime <= wo.lastHeartBeatTime && Time.realtimeSinceStartup - wo.lastHeartBeatTime >= heartBeatTimeout)
             {
                 // 心跳超时,认为连接已经断开
                 ProcessDisconnectUnexpected(wo);
             }
         }
         // 再次检查连接器状态,如果一切正常,那么就可以检查并发送心跳
         if (wo.connected && !wo.reconnect && wo.connector.State == EConnectorState.ExpectConnected)
         {
             if (Time.realtimeSinceStartup - wo.lastHeartBeatTime >= wo.heartBeatInterval)
             {
                 wo.connector.Send(heartBeatPack, 0, heartBeatPack.Length);
                 wo.lastHeartBeatTime = Time.realtimeSinceStartup;
             }
         }
     }
 }
Exemplo n.º 3
0
 public void ReleaseIt(IConnector connector)
 {
     for (int i = 0; i < connectorsUnderWatchList.Count; ++i)
     {
         WatchObject tmp = connectorsUnderWatchList[i];
         if (tmp != null && tmp.connector == connector)
         {
             ReturnWatchObjectToPool(tmp);
             connectorsUnderWatchList.RemoveAt(i);
             break;
         }
     }
 }
Exemplo n.º 4
0
 private void ProcessDisconnected(WatchObject wo)
 {
     wo.connected = false;
     if (!wo.reconnect)
     {
         // 非重连的情况下,触发断开连接成功的回调(重连状况下,不触发回调而是进入等待重连流程)
         if (wo.eventHandler != null)
         {
             wo.eventHandler.OnDisconnected();
         }
     }
     wo.lastHeartBeatTime       = 0f;
     wo.lastHeartBeatReturnTime = 0f;
 }
Exemplo n.º 5
0
 private void CheckAllConnectors()
 {
     for (int i = 0; i < connectorsUnderWatchList.Count; ++i)
     {
         WatchObject wo = connectorsUnderWatchList[i];
         if (wo == null || wo.connector == null)                     // 无效的WatchObject
         {
             continue;
         }
         CheckHeartBeat(wo);
         CheckConnectorState(wo);
         CheckConnectorReceive(wo);
         CheckConnectorSend(wo);
     }
 }
Exemplo n.º 6
0
        private WatchObject LoadWatchObject(DataGridViewRow row_obj)
        {
            if ((row_obj == null) ||
                (row_obj.IsNewRow)
                )
            {
                return(null);
            }

            /* 現在のセル設定をWatchDataConfigに変換する */
            var config = LoadWatchDataConfig(row_obj);

            /* 変換できなかったり有効設定でない場合は監視しない */
            if ((config == null) ||
                (!config.Enable)
                )
            {
                return(null);
            }

            /* フィルターが有効でない場合は監視しない */
            var filter = PacketFilterController.Build(config.Expression);

            if (filter == null)
            {
                return(null);
            }

            /* 監視オブジェクト更新 */
            var watch_obj = row_obj.Tag as WatchObject;

            if ((watch_obj == null) ||
                (watch_obj.Config.Expression != config.Expression)
                )
            {
                watch_obj = new WatchObject(config, filter);
            }
            else
            {
                watch_obj.Config.WatchTarget = config.WatchTarget;
                watch_obj.Config.NtfEvent    = config.NtfEvent;
                watch_obj.Config.NtfDialog   = config.NtfDialog;
                watch_obj.Config.NtfMail     = config.NtfMail;
            }

            return(watch_obj);
        }
Exemplo n.º 7
0
        public void DaemonIt(IConnector connector, DaemonParameter daemonParam)
        {
            for (int i = 0; i < connectorsUnderWatchList.Count; ++i)
            {
                WatchObject tmp = connectorsUnderWatchList[i];
                if (tmp != null && tmp.connector == connector)
                {
                    if (LogUtil.ShowWarning != null)
                    {
                        LogUtil.ShowWarning("这个connector已经处于守护之下,不能重复添加");
                    }
                    return;
                }
            }
            WatchObject wo = GetWatchObjectFromPool();

            wo.Init(connector, daemonParam);
            connectorsUnderWatchList.Add(wo);
        }
Exemplo n.º 8
0
 private void ProcessDisconnectUnexpected(WatchObject wo)
 {
     // 触发意外断开回调
     if (wo.eventHandler != null)
     {
         wo.eventHandler.OnDisconnectedUnexpected();
     }
     // 如果需要重连,标记重连
     if (wo.autoReconnect)
     {
         wo.reconnect = true;
         // 重置参数
         wo.autoReconnectRetryCount    = 0;
         wo.autoReconnectLastRetryTime = Time.realtimeSinceStartup;
     }
     // 主动断开连接,以便标志位状态同步
     wo.connector.BeginDisconnect();
     wo.lastHeartBeatTime       = 0f;
     wo.lastHeartBeatReturnTime = 0f;
 }
Exemplo n.º 9
0
        /// <summary>守护线程</summary>
        public void WatchThreading(int time, tg_task newtask)
        {
            try
            {
                var obj = new WatchObject {
                    user_id = newtask.user_id, task_id = newtask.id, time = time,
                };
                var token = new CancellationTokenSource();

                Task.Factory.StartNew(m =>
                {
                    var wo = m as WatchObject;
                    if (wo == null)
                    {
                        return;
                    }
                    var key = wo.GetKey();
                    Variable.CD.AddOrUpdate(key, false, (k, v) => false);
                    SpinWait.SpinUntil(() =>
                    {
                        if (!Variable.CD.ContainsKey(key))
                        {
                            token.Cancel();
                            return(true);
                        }
                        if (Convert.ToBoolean(Variable.CD[key]))
                        {
                            token.Cancel();
                            return(true);
                        }
                        var watch = Common.GetInstance().GetWorkInfo(wo.user_id);
                        if (watch.WatchState == (int)TaskKillType.LOSE)
                        {
                            watch.WatchState = 0;
                            watch.WatchNpcid = 0;
                            watch.P_State    = 0;
                            token.Cancel();
                            return(true);
                        }
                        return(false);
                    }, wo.time);
                }, obj, token.Token).ContinueWith((m, n) =>
                {
                    var wo = n as WatchObject;
                    if (wo == null)
                    {
                        token.Cancel(); return;
                    }
                    WatchEnd(Convert.ToInt64(wo.task_id));
                    //移除全局变量
                    var key = wo.GetKey();
                    bool r;
                    Variable.CD.TryRemove(key, out r);
                    token.Cancel();
                }, obj, token.Token);
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 开启新线程
        /// </summary>
        /// <param name="time"></param>
        /// <param name="mytask"></param>
        /// <param name="finishstep"></param>
        public void NewTaskStart(decimal time, tg_task mytask, string finishstep)
        {
#if DEBUG
            time = 10;
#endif
            try
            {
                var temp = new WatchObject()
                {
                    task_id     = mytask.id,
                    time        = (int)time,
                    user_id     = mytask.user_id,
                    step_string = finishstep
                };
                var token = new CancellationTokenSource();
                Task.Factory.StartNew(m =>
                {
                    var t = m as WatchObject;
                    if (t == null)
                    {
                        return;
                    }
                    var key = t.GetKey();
                    Variable.CD.AddOrUpdate(key, false, (k, v) => false);
                    SpinWait.SpinUntil(() =>
                    {
                        if (!Variable.CD.ContainsKey(key))
                        {
                            token.Cancel();
                            return(true);
                        }
                        if (Convert.ToBoolean(Variable.CD[key]))
                        {
                            token.Cancel();
                            return(true);
                        }
                        var w = Common.GetInstance().GetWorkInfo(t.user_id);
                        if (w.GuardSceneId == 0)
                        {
                            token.Cancel();
                            return(true);
                        }
                        return(false);
                    }, temp.time * 1000);
                }, temp, token.Token).ContinueWith((m, n) =>
                {
                    var wo = n as WatchObject;
                    if (wo == null)
                    {
                        token.Cancel(); return;
                    }
                    TaskUpdateAndSend(wo.task_id, wo.step_string);
                    var key = wo.GetKey();
                    bool r;
                    Variable.CD.TryRemove(key, out r);
                    token.Cancel();
                }, temp, token.Token);
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
            }
        }
Exemplo n.º 11
0
 private void CheckConnectorReceive(WatchObject wo)
 {
     if (!wo.connector.IsReceiving)
     {
         // 连接器不在接收状态,那么将当前buffer中已经接收到的数据进行处理
         while (!wo.receiveBuffer.IsEmpty)
         {
             // 拆包,按完整消息返回给Handler
             // 寻找魔数
             if (!wo.receiveBuffer.DiscardToFirstIndexOf(0xC8, 0xEF))
             {
                 wo.receiveBuffer.DiscardAll();
             }
             if (wo.receiveBuffer.Length >= 8)
             {
                 // 找到了魔数,而且数据长度够一个消息头
                 // 解析消息头
                 byte[] lenBytes = new byte[2];
                 wo.receiveBuffer.Peek(2, out lenBytes[0]);
                 wo.receiveBuffer.Peek(3, out lenBytes[1]);
                 short len = BitConverterEx.GetShort(lenBytes, 0, true);
                 byte  ver;
                 wo.receiveBuffer.Peek(4, out ver);
                 byte serializeType;
                 wo.receiveBuffer.Peek(5, out serializeType);
                 byte moduleID;
                 wo.receiveBuffer.Peek(6, out moduleID);
                 byte functionID;
                 wo.receiveBuffer.Peek(7, out functionID);
                 // TODO 区分协议版本号和序列化类型?
                 // TODO 按模块号分发?
                 // 收到心跳,记录下收到的时间
                 if (moduleID == heartBeatModuleID && functionID == heartBeatReturnFunctionID)
                 {
                     wo.lastHeartBeatReturnTime = Time.realtimeSinceStartup;
                 }
                 // 消息头丢弃
                 wo.receiveBuffer.Discard(8);
                 // 如果存在协议体,那么尝试处理协议体
                 if (len > 8)
                 {
                     byte[] msgBytes = new byte[len - 8];
                     if (wo.receiveBuffer.TryPull(msgBytes.Length, ref msgBytes))
                     {
                         wo.eventHandler.OnReceive(moduleID, functionID, msgBytes);
                     }
                     else
                     {
                         // 消息接收长度还不够,继续接收
                         Debug.Log(Time.frameCount + " 继续接收1");
                         break;
                     }
                 }
             }
             else
             {
                 // 消息接收长度还不够,继续接收
                 Debug.Log(Time.frameCount + " 继续接收2");
                 break;
             }
         }
         if (wo.connected && wo.connector.State == EConnectorState.ExpectConnected && wo.connector.HasDataAvailable)
         {
             // 如果当前处于连接状态,就再次发起接收
             wo.connector.Receive(wo.receiveBuffer);
         }
     }
 }
Exemplo n.º 12
0
 private void CheckConnectorState(WatchObject wo)
 {
     if (!wo.connected)              // 如果上一次检查时连接器状态是断开状态
     {
         if (wo.connector.State == EConnectorState.ExpectHasIpAddress)
         {
             // 如果连接器已经解析好了IP地址,但是没有连接上,也没有在等待连接,那么认为连接器处在刚刚解析完域名等待调用连接的状态,调用连接
             wo.connector.BeginConnect();
         }
         else if (wo.connector.State == EConnectorState.ExpectConnected)
         {
             // 如果连接器上一次检测时还没有连接上,但是现在已经连接上了,那么认为连接器刚刚连接成功
             wo.connected = true;
             if (!wo.reconnect)
             {
                 // 非重连的情况下,触发连接成功回调
                 if (wo.eventHandler != null)
                 {
                     wo.eventHandler.OnConnected();
                 }
             }
             else
             {
                 // 重连状况下,触发重连成功回调,并退出重连流程
                 wo.reconnect = false;
                 if (wo.eventHandler != null)
                 {
                     wo.eventHandler.OnReconnectedByDaemon();
                 }
             }
         }
         else if (wo.connector.State == EConnectorState.ExpectDisconnected || wo.connector.State == EConnectorState.Initial)
         {
             // 连接器处于断开状态,并且已进入重连流程,那么按照参数指定的周期尝试连接
             if (wo.reconnect)
             {
                 if (wo.autoReconnectRetryCount >= wo.autoReconnectRetryMax)
                 {
                     // 已经超过最大重试次数,退出重连流程
                     wo.reconnect = false;
                     // 触发重连失败的回调
                     if (wo.eventHandler != null)
                     {
                         wo.eventHandler.OnReconnectFailed();
                     }
                 }
                 else if (Time.realtimeSinceStartup - wo.autoReconnectLastRetryTime > wo.autoReconnectRetryInterval)
                 {
                     // 重试间隔已到,发起重连,并记录这一次重试的时间,重试次数加1
                     wo.autoReconnectLastRetryTime = Time.realtimeSinceStartup;
                     ++wo.autoReconnectRetryCount;
                     wo.connector.BeginConnect();
                 }
             }
         }
     }
     else                // 如果上一次检查时连接器状态是连接状态
     {
         // 判断连接意外断开改成用心跳判断
         //if (wo.connector.State == EConnectorState.ExpectConnected && !wo.connector.IsSending && !wo.connector.IsReceiving && !wo.connector.Connected)
         //{
         //	// 期望处于连接状态,但实际上并没有连接上,可以认为是意外断开了
         //	ProcessDisconnectUnexpected(wo);
         //}
         //else
         if (wo.connector.State == EConnectorState.ExpectDisconnected || wo.connector.State == EConnectorState.Initial)
         {
             // 如果连接器上一次检测时是连接上的,但是现在连接断开了,那么认为连接器刚刚断开连接
             ProcessDisconnected(wo);
         }
     }
 }
Exemplo n.º 13
0
 private void ReturnWatchObjectToPool(WatchObject wo)
 {
     wo.Clear();
     watchObjectPool.Enqueue(wo);
 }