Exemplo n.º 1
0
 /// <summary>
 /// 关闭客户端连接
 /// </summary>
 /// <param name="session"></param>
 public void CloseClientSocket(MyWebSocketBehavior handler)
 {
     try
     {
         handler.Context.WebSocket.Close();
     }
     catch (Exception ex)
     {
         CommonInfo.Output("断开客户端异常:{0}", ex.Message);
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// 后台线程方法
        /// 主要处理客户端连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DoWorkCheckMethod(object sender, DoWorkEventArgs e)
        {
            int timeout = HeartBeatSecond * 3;//连续3次检测无心跳 则表示客户端已死掉了

            while (IsRunning)
            {
                try
                {
                    _doWorkARE.Reset();
                    _doWorkARE.WaitOne(HeartBeatSecond);

                    //定时清理任务
                    HandlerTaskManager.ClearTask();

                    foreach (WebSocketServiceHost host in _httpServer.WebSocketServices.Hosts)
                    {
                        List <IWebSocketSession> tempList = host.Sessions.Sessions.ToList();
                        foreach (var item in tempList)
                        {
                            MyWebSocketBehavior handler = item as MyWebSocketBehavior;
                            if (handler != null)
                            {
                                //检测连接
                                if ((DateTime.Now - handler.LastRecvTime).TotalSeconds > timeout)
                                {
                                    //断开客户端连接
                                    CloseClientSocket(handler);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    CommonInfo.Output("检测连接异常:{0}", ex.Message);
                }
            }
        }