public void ConnectToServer(IPEndPoint ipEndPoint) { Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var awaiter = HandlerSaeaPool.Take(); awaiter.Saea.RemoteEndPoint = ipEndPoint; SaeaExHelper.ConnectAsync(socket, awaiter, (a, e) => { HandlerSaeaPool.Return(a); var session = SessionPool.Take(); if (e != SocketError.Success) { LogHelper.WriteLog("client_connect-error"); CompletetionNotify?.Invoke(TcpSocketCompletionNotify.OnClosed, session); SessionPool.Return(session); return; } TcpSocketSaeaSessions.Add(session); session.Attach(socket); CompletetionNotify?.Invoke(TcpSocketCompletionNotify.OnConnected, session); session.StartProcess(); }); }
private void AppKeepAliveWorkThread() { byte[] emptyHeart = new byte[] { 0, 0, 0, 0 }; while (this._isRuning) { for (int i = 0; i < TcpSocketSaeaSessions.Count; i++) { var session = (TcpSocketSaeaPackBased)TcpSocketSaeaSessions[i]; if (session.State != TcpSocketConnectionState.Connected) { LogHelper.WriteLog("server_heart_thread != Connected"); TcpSocketSaeaSessions.RemoveAt(i); i--; continue; } if ((int)(DateTime.Now - session._heartTime).TotalSeconds > 20) { LogHelper.WriteLog("server_heart_thread_timeout --state:" + session.State.ToString() + " present_time:" + DateTime.Now.ToString() + " heart_time:" + session._heartTime.ToString()); if (session.State == TcpSocketConnectionState.Connected) { Console.WriteLine("server timeout--"); session.Close(true); TcpSocketSaeaSessions.RemoveAt(i); i--; } } } Thread.Sleep(5000); } }
public virtual void DisconnectAll(bool notify) { foreach (TcpSocketSaeaSession session in TcpSocketSaeaSessions) { session.Close(notify); } TcpSocketSaeaSessions.Clear(); }
private void AppKeepAliveWorkThread() { byte[] emptyHeart = new byte[] { 0, 0, 0, 0 }; while (this._isRuning) { for (int i = 0; i < TcpSocketSaeaSessions.Count; i++) { var session = (TcpSocketSaeaPackBased)TcpSocketSaeaSessions[i]; if (session.State == TcpSocketConnectionState.Closed) { LogHelper.WriteLog("client_heart_thread = Closed"); TcpSocketSaeaSessions.RemoveAt(i); i--; continue; } if ((int)(DateTime.Now - session._heartTime).TotalSeconds > 20) { LogHelper.WriteLog("client_heart_thread_timeout ! state:" + session.State.ToString() + " present_time:" + DateTime.Now.ToString() + " heart_time:" + session._heartTime.ToString()); if (session.State == TcpSocketConnectionState.Connected) { session.Close(true); TcpSocketSaeaSessions.RemoveAt(i); i--; } } else { //如果数据正在发送,就不发送心跳 if (session._intervalIsUseChannel == 0) { var awaiter = HandlerSaeaPool.Take(); //4个字节空包头 awaiter.Saea.SetBuffer(emptyHeart, 0, emptyHeart.Length); SaeaExHelper.SendAsync(session.Socket, awaiter, (a, e) => HandlerSaeaPool.Return(a)); } } } Thread.Sleep(5000); } }