private void SessionFor(object obj) { do { for (int i = 0; i < this.sessionList.Length; i++) { if (sessionList[i] != null) { //清除超时的 DateTime outT = sessionList[i].LastActively.AddSeconds(this.SessionTimeOut); int n = DateTime.Now.CompareTo(outT); if (n > 0)//超时 { if (OnSessionClosed != null) { OnSessionClosed(sessionList[i], ""); } SocketSession session = this.sessionList[i]; StopSession(ref session); } //清除连接已关闭的。 if (sessionList[i] != null && !sessionList[i].ClientSocket.Connected) { if (OnSessionClosed != null) { OnSessionClosed(sessionList[i], ""); } SocketSession session = this.sessionList[i]; StopSession(ref session); } } } Thread.Sleep(400); //session过期时间单位为秒,停顿400毫秒遍历一次Session } while (true); }
/// <summary> /// 停止某个会话。 /// </summary> /// <param name=”scs”></param> private void StopSession(ref SocketSession scs) { if (scs != null) { scs.StopSession(); } scs = null; }
/// <summary> /// 接收用户连接,开启新线程处理新的连接 /// </summary> /// <param name=”ar”>新链接的socket对象</param> private void AcceptCallback(IAsyncResult ar) { allDone.Set(); try { bool IsNeedWait = true; do { if (!_IsRuning) { return; } //if (this.sessionList.Count < this._MaxQueue) //{ // Socket handler = listener.EndAccept(ar); // if (handler != null) // { // //获取客户端链接,创建会话。 // SocketSession sckObj = new SocketSession(handler); // this.sessionList.Add(sckObj); // OnSessionCreated(sckObj, ""); // IsNeedWait = false; // } //} #region for (int i = 0; i < this._MaxQueue; i++) { if (!_IsRuning) { return; } //查找队列空余 if (this.sessionList[i] == null) { Socket handler = listener.EndAccept(ar); //获取客户端链接,创建会话。 SocketSession sckObj = new SocketSession(handler); this.sessionList[i] = sckObj; OnSessionCreated(sckObj, ""); IsNeedWait = false; break; } } #endregion if (IsNeedWait)//队列已满,排队等待。 { OnSessionFull(this, ""); Thread.Sleep(600); } }while(IsNeedWait); } catch (System.Exception e) { OnError(e, this); } }
/// <summary> /// 停止服务。 /// </summary> public void Stop() { if (!_IsRuning) { return; } _IsRuning = false; try { //停止监听的socket this.listener.Close(); } catch (System.Exception e) { OnError(e, this); } //停止所有的会话连接及线程。 for (int i = 0; i < this.sessionList.Length; i++) { SocketSession session = this.sessionList[i]; StopSession(ref session); } OnServerStop(this, ""); }