using HslCommunication.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using HslCommunication.Core.Net; using System.Net; using System.Net.Sockets; namespace HslCommunication.Enthernet { /// /// 一个基于异步高性能的客户端网络类,支持主动接收服务器的消息 /// /// /// 详细的使用说明,请参照博客http://www.cnblogs.com/dathlin/p/7697782.html /// /// /// 此处贴上了Demo项目的服务器配置的示例代码 /// /// public class NetComplexClient : NetworkXBase { #region Constructor /// /// 实例化一个对象 /// public NetComplexClient( ) { session = new AppSession( ); ServerTime = DateTime.Now; EndPointServer = new IPEndPoint( IPAddress.Any, 0 ); } #endregion #region Private Member private AppSession session; // 客户端的核心连接对象 private int isConnecting = 0; // 指示客户端是否处于连接服务器中,0代表未连接,1代表连接中 private bool IsQuie = false; // 指示系统是否准备退出 private Thread thread_heart_check = null; // 心跳线程 #endregion #region Public Properties /// /// 客户端系统是否启动 /// public bool IsClientStart { get; set; } /// /// 重连接失败的次数 /// public int ConnectFailedCount { get; private set; } /// /// 客户端登录的标识名称,可以为ID号,也可以为登录名 /// public string ClientAlias { get; set; } = string.Empty; /// /// 远程服务器的IP地址和端口 /// public IPEndPoint EndPointServer { get; set; } /// /// 服务器的时间,自动实现和服务器同步 /// public DateTime ServerTime { get; private set; } /// /// 系统与服务器的延时时间,单位毫秒 /// public int DelayTime { get; private set; } #endregion #region Event Handle /// /// 客户端启动成功的事件,重连成功也将触发此事件 /// public event Action LoginSuccess; /// /// 连接失败时触发的事件 /// public event Action LoginFailed; /// /// 服务器的异常,启动,等等一般消息产生的时候,出发此事件 /// public event Action MessageAlerts; /// /// 在客户端断开后并在重连服务器之前触发,用于清理系统资源 /// public event Action BeforReConnected; /// /// 当接收到文本数据的时候,触发此事件 /// public event Action AcceptString; /// /// 当接收到字节数据的时候,触发此事件 /// public event Action AcceptByte; #endregion #region Start Close Support /// /// 关闭该客户端引擎 /// public void ClientClose( ) { IsQuie = true; if (IsClientStart) SendBytes( session, HslProtocol.CommandBytes( HslProtocol.ProtocolClientQuit, 0, Token, null ) ); IsClientStart = false; // 关闭客户端 thread_heart_check = null; LoginSuccess = null; // 清空所有的事件 LoginFailed = null; MessageAlerts = null; AcceptByte = null; AcceptString = null; try { session.WorkSocket?.Shutdown( SocketShutdown.Both ); session.WorkSocket?.Close( ); } catch { } LogNet?.WriteDebug( ToString( ), "Client Close." ); } /// /// 启动客户端引擎,连接服务器系统 /// public void ClientStart() { // 如果处于连接中就退出 if (Interlocked.CompareExchange( ref isConnecting, 1, 0 ) != 0) return; // 启动后台线程连接 new Thread( new ThreadStart( ThreadLogin ) ) { IsBackground = true }.Start( ); // 启动心跳线程,在第一次Start的时候 if (thread_heart_check == null) { thread_heart_check = new Thread( new ThreadStart( ThreadHeartCheck ) ) { Priority = ThreadPriority.AboveNormal, IsBackground = true }; thread_heart_check.Start( ); } } /// /// 连接服务器之前的消息提示,如果是重连的话,就提示10秒等待信息 /// private void AwaitToConnect( ) { if (ConnectFailedCount == 0) { MessageAlerts?.Invoke( StringResources.Language.ConnectingServer ); } else { int count = 10; while (count > 0) { if (IsQuie) return; count--; MessageAlerts?.Invoke( string.Format( StringResources.Language.ConnectFailedAndWait, count ) ); Thread.Sleep( 1000 ); } MessageAlerts?.Invoke( string.Format( StringResources.Language.AttemptConnectServer, ConnectFailedCount ) ); } } private void ConnectFailed( ) { ConnectFailedCount++; Interlocked.Exchange( ref isConnecting, 0 ); LoginFailed?.Invoke( ConnectFailedCount ); LogNet?.WriteDebug( ToString( ), "Connected Failed, Times: " + ConnectFailedCount ); } private OperateResult ConnectServer( ) { OperateResult connectResult = CreateSocketAndConnect( EndPointServer, 10000 ); if (!connectResult.IsSuccess) { return connectResult; } // 连接成功,发送数据信息 OperateResult sendResult = SendStringAndCheckReceive( connectResult.Content, 1, ClientAlias ); if (!sendResult.IsSuccess) { return OperateResult.CreateFailedResult( sendResult ); } MessageAlerts?.Invoke( StringResources.Language.ConnectServerSuccess ); return connectResult; } private void LoginSuccessMethod( Socket socket ) { ConnectFailedCount = 0; try { session.IpEndPoint = (IPEndPoint)socket.RemoteEndPoint; session.LoginAlias = ClientAlias; session.WorkSocket = socket; session.HeartTime = DateTime.Now; IsClientStart = true; ReBeginReceiveHead( session, false ); } catch(Exception ex) { LogNet?.WriteException( ToString( ), ex ); } } private void ThreadLogin() { // 连接的消息等待 AwaitToConnect( ); OperateResult connectResult = ConnectServer( ); if (!connectResult.IsSuccess) { ConnectFailed( ); // 连接失败,重新连接服务器 ThreadPool.QueueUserWorkItem( new WaitCallback( ReconnectServer ), null ); return; } // 登录成功 LoginSuccessMethod( connectResult.Content ); // 登录成功 LoginSuccess?.Invoke( ); Interlocked.Exchange( ref isConnecting, 0 ); Thread.Sleep( 200 ); } private void ReconnectServer(object obj = null) { // 是否连接服务器中,已经在连接的话,则不再连接 if (isConnecting == 1) return; // 是否退出了系统,退出则不再重连 if (IsQuie) return; // 触发连接失败,重连系统前错误 BeforReConnected?.Invoke( ); session?.WorkSocket?.Close( ); // 重新启动客户端 ClientStart( ); } #endregion #region Send Message Support /// /// 通信出错后的处理 /// /// 接收的会话 /// 异常 internal override void SocketReceiveException( AppSession receive, Exception ex ) { if (ex.Message.Contains( StringResources.Language.SocketRemoteCloseException )) { // 异常掉线 ReconnectServer( ); } else { // MessageAlerts?.Invoke("数据接收出错:" + ex.Message); } LogNet?.WriteDebug( ToString( ), "Socket Excepiton Occured." ); } /// /// 服务器端用于数据发送文本的方法 /// /// 用户自定义的命令头 /// 发送的文本 public void Send( NetHandle customer, string str ) { if (IsClientStart) { SendBytes( session, HslProtocol.CommandBytes( customer, Token, str ) ); } } /// /// 服务器端用于发送字节的方法 /// /// 用户自定义的命令头 /// 实际发送的数据 public void Send( NetHandle customer, byte[] bytes ) { if (IsClientStart) { SendBytes( session, HslProtocol.CommandBytes( customer, Token, bytes ) ); } } private void SendBytes( AppSession stateone, byte[] content ) { SendBytesAsync( stateone, content ); } #endregion #region Data Process Center /// /// 客户端的数据处理中心 /// /// 会话 /// 消息暗号 /// 用户消息 /// 数据内容 internal override void DataProcessingCenter( AppSession session, int protocol, int customer, byte[] content ) { if (protocol == HslProtocol.ProtocolCheckSecends) { DateTime dt = new DateTime( BitConverter.ToInt64( content, 0 ) ); ServerTime = new DateTime( BitConverter.ToInt64( content, 8 ) ); DelayTime = (int)(DateTime.Now - dt).TotalMilliseconds; this.session.HeartTime = DateTime.Now; // MessageAlerts?.Invoke("心跳时间:" + DateTime.Now.ToString()); } else if (protocol == HslProtocol.ProtocolClientQuit) { // 申请了退出 } else if (protocol == HslProtocol.ProtocolUserBytes) { // 接收到字节数据 AcceptByte?.Invoke( this.session, customer, content ); } else if (protocol == HslProtocol.ProtocolUserString) { // 接收到文本数据 string str = Encoding.Unicode.GetString( content ); AcceptString?.Invoke( this.session, customer, str ); } } #endregion #region Heart Check /// /// 心跳线程的方法 /// private void ThreadHeartCheck() { Thread.Sleep( 2000 ); while (true) { Thread.Sleep( 1000 ); if (!IsQuie) { byte[] send = new byte[16]; BitConverter.GetBytes( DateTime.Now.Ticks ).CopyTo( send, 0 ); SendBytes( session, HslProtocol.CommandBytes( HslProtocol.ProtocolCheckSecends, 0, Token, send ) ); double timeSpan = (DateTime.Now - session.HeartTime).TotalSeconds; if (timeSpan > 1 * 8)//8次没有收到失去联系 { if (isConnecting == 0) { LogNet?.WriteDebug( ToString( ), $"Heart Check Failed int {timeSpan} Seconds." ); ReconnectServer( ); } if (!IsQuie) Thread.Sleep( 1000 ); } } else { break; } } } #endregion #region Object Override /// /// 返回对象的字符串表示形式 /// /// public override string ToString() { return "NetComplexClient"; } #endregion } }