/// <summary> /// 数据处理中心 /// </summary> /// <param name="receive"></param> /// <param name="protocol"></param> /// <param name="customer"></param> /// <param name="content"></param> internal override void DataProcessingCenter(AsyncStateOne receive, int protocol, int customer, byte[] content) { if (protocol == HslProtocol.ProtocolCheckSecends) { BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(content, 8); SendBytes(receive, NetSupport.CommandBytes(HslProtocol.ProtocolCheckSecends, customer, KeyToken, content)); receive.HeartTime = DateTime.Now; } else if (protocol == HslProtocol.ProtocolClientQuit) { TcpStateDownLine(receive, true); } else if (protocol == HslProtocol.ProtocolUserBytes) { //接收到字节数据 AcceptByte?.Invoke(receive, customer, content); // LogNet?.WriteDebug(LogHeaderText, "Protocol:" + protocol + " customer:" + customer + " name:" + receive.LoginAlias); } else if (protocol == HslProtocol.ProtocolUserString) { //接收到文本数据 string str = Encoding.Unicode.GetString(content); AcceptString?.Invoke(receive, customer, str); // LogNet?.WriteDebug(LogHeaderText, "Protocol:" + protocol + " customer:" + customer + " name:" + receive.LoginAlias); } }
/// <summary> /// 客户端的数据处理中心 /// </summary> /// <param name="receive"></param> /// <param name="protocol"></param> /// <param name="customer"></param> /// <param name="content"></param> internal override void DataProcessingCenter(AsyncStateOne receive, 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; stateone.HeartTime = DateTime.Now; // MessageAlerts?.Invoke("心跳时间:" + DateTime.Now.ToString()); } else if (protocol == HslProtocol.ProtocolClientQuit) { // 申请了退出 } else if (protocol == HslProtocol.ProtocolUserBytes) { // 接收到字节数据 AcceptByte?.Invoke(stateone, customer, content); } else if (protocol == HslProtocol.ProtocolUserString) { // 接收到文本数据 string str = Encoding.Unicode.GetString(content); AcceptString?.Invoke(stateone, customer, str); } }
internal override void SocketReceiveException(AsyncStateOne receive, Exception ex) { if (ex.Message.Contains(StringResources.SocketRemoteCloseException)) { //异常掉线 TcpStateDownLine(receive, false); } }
/// <summary> /// 重新开始接收数据 /// </summary> /// <exception cref="ArgumentNullException"></exception> /// private void RefreshReceive() { AsyncStateOne state = new AsyncStateOne(); state.WorkSocket = WorkSocket; state.UdpEndPoint = new IPEndPoint(IPAddress.Any, 0); state.BytesContent = new byte[ReceiveCacheLength]; //WorkSocket.BeginReceiveFrom(state.BytesHead, 0, 8, SocketFlags.None, ref state.UdpEndPoint, new AsyncCallback(ReceiveAsyncCallback), state); WorkSocket.BeginReceiveFrom(state.BytesContent, 0, ReceiveCacheLength, SocketFlags.None, ref state.UdpEndPoint, new AsyncCallback(AsyncCallback), state); }
/// <summary> /// 通信出错后的处理 /// </summary> /// <param name="receive"></param> /// <param name="ex"></param> internal override void SocketReceiveException(AsyncStateOne receive, Exception ex) { if (ex.Message.Contains(StringResources.SocketRemoteCloseException)) { // 异常掉线 ReconnectServer(); } else { // MessageAlerts?.Invoke("数据接收出错:" + ex.Message); } LogNet?.WriteDebug(LogHeaderText, "Socket Excepiton Occured."); }
/*********************************************************************************************************** * * 无法使用如下的字节头接收来确认网络传输,总是报错为最小 * ***********************************************************************************************************/ //private void ReceiveAsyncCallback(IAsyncResult ar) //{ // if (ar.AsyncState is AsyncStateOne state) // { // try // { // state.AlreadyReceivedHead += state.WorkSocket.EndReceiveFrom(ar, ref state.UdpEndPoint); // if (state.AlreadyReceivedHead < state.HeadLength) // { // //接续接收头数据 // WorkSocket.BeginReceiveFrom(state.BytesHead, state.AlreadyReceivedHead, state.HeadLength - state.AlreadyReceivedHead, SocketFlags.None, // ref state.UdpEndPoint, new AsyncCallback(ReceiveAsyncCallback), state); // } // else // { // //开始接收内容 // int ReceiveLenght = BitConverter.ToInt32(state.BytesHead, 4); // if (ReceiveLenght > 0) // { // state.BytesContent = new byte[ReceiveLenght]; // WorkSocket.BeginReceiveFrom(state.BytesContent, state.AlreadyReceivedContent, state.BytesContent.Length - state.AlreadyReceivedContent, // SocketFlags.None, ref state.UdpEndPoint, new AsyncCallback(ContentReceiveAsyncCallback), state); // } // else // { // //没有内容了 // ThreadDealWithReveice(state, BitConverter.ToInt32(state.BytesHead, 0), state.BytesContent); // state = null; // RefreshReceive(); // } // } // } // catch(Exception ex) // { // LogHelper.SaveError(StringResources.异步数据结束挂起发送出错, ex); // } // } //} //private void ContentReceiveAsyncCallback(IAsyncResult ar) //{ // if (ar.AsyncState is AsyncStateOne state) // { // try // { // state.AlreadyReceivedContent += state.WorkSocket.EndReceiveFrom(ar, ref state.UdpEndPoint); // if (state.AlreadyReceivedContent < state.BytesContent.Length) // { // //还需要继续接收 // WorkSocket.BeginReceiveFrom(state.BytesContent, state.AlreadyReceivedContent, state.BytesContent.Length - state.AlreadyReceivedContent, // SocketFlags.None, ref state.UdpEndPoint, new AsyncCallback(ContentReceiveAsyncCallback), state); // } // else // { // //接收完成了 // ThreadDealWithReveice(state, BitConverter.ToInt32(state.BytesHead, 0), new byte[0]); // state = null; // RefreshReceive(); // } // } // catch (Exception ex) // { // LogHelper.SaveError(StringResources.异步数据结束挂起发送出错, ex); // } // } //} #region 数据中心处理块 /// <summary> /// 数据处理中心 /// </summary> /// <param name="receive"></param> /// <param name="protocol"></param> /// <param name="customer"></param> /// <param name="content"></param> internal override void DataProcessingCenter(AsyncStateOne receive, int protocol, int customer, byte[] content) { LogNet?.WriteDebug(LogHeaderText, "Protocol:" + protocol + " customer:" + customer + " ip:" + receive.GetRemoteEndPoint().Address.ToString()); if (protocol == HslCommunicationCode.Hsl_Protocol_User_Bytes) { AcceptByte?.Invoke(receive, customer, content); } else if (protocol == HslCommunicationCode.Hsl_Protocol_User_String) { //接收到文本数据 string str = Encoding.Unicode.GetString(content); AcceptString?.Invoke(receive, customer, str); } }
private void TcpStateUpLine(AsyncStateOne state) { HybirdLockSockets.Enter(); All_sockets_connect.Add(state); HybirdLockSockets.Leave(); // 提示上线 ClientOnline?.Invoke(state); // 是否保存上线信息 if (IsSaveLogClientLineChange) { LogNet?.WriteInfo(LogHeaderText, "IP:" + state.IpAddress + " Name:" + state?.LoginAlias + " " + StringResources.NetClientOnline); } // 计算客户端在线情况 AsyncCoordinator.StartOperaterInfomation(); }
private void TcpStateDownLine(AsyncStateOne state, bool is_regular) { HybirdLockSockets.Enter(); All_sockets_connect.Remove(state); HybirdLockSockets.Leave(); // 关闭连接 TcpStateClose(state); // 判断是否正常下线 string str = is_regular ? StringResources.NetClientOffline : StringResources.NetClientBreak; ClientOffline?.Invoke(state, str); // 是否保存上线信息 if (IsSaveLogClientLineChange) { LogNet?.WriteInfo(LogHeaderText, "IP:" + state.IpAddress + " Name:" + state?.LoginAlias + " " + str); } // 计算客户端在线情况 AsyncCoordinator.StartOperaterInfomation(); }
private void SendBytes(AsyncStateOne stateone, byte[] content) { SendBytesAsync(stateone, content); }
/// <summary> /// 服务器端用于发送字节的方法 /// </summary> /// <param name="stateone">数据发送对象</param> /// <param name="customer">用户自定义的数据对象,如不需要,赋值为0</param> /// <param name="bytes">实际发送的数据</param> public void Send(AsyncStateOne stateone, NetHandle customer, byte[] bytes) { SendBytes(stateone, NetSupport.CommandBytes(customer, KeyToken, bytes)); }
/// <summary> /// 服务器端用于数据发送文本的方法 /// </summary> /// <param name="stateone">数据发送对象</param> /// <param name="customer">用户自定义的数据对象,如不需要,赋值为0</param> /// <param name="str">发送的文本</param> public void Send(AsyncStateOne stateone, NetHandle customer, string str) { SendBytes(stateone, NetSupport.CommandBytes(customer, KeyToken, str)); }
/// <summary> /// 登录后的处理方法 /// </summary> /// <param name="obj"></param> protected override void ThreadPoolLogin(object obj) { if (obj is Socket socket) { // 判断连接数是否超出规定 if (All_sockets_connect.Count > ConnectMax) { socket?.Close(); LogNet?.WriteWarn(LogHeaderText, StringResources.NetClientFull); return; } // 接收用户别名并验证令牌 OperateResult result = new OperateResult(); if (!ReceiveStringFromSocket( socket, out int customer, out string login_alias, result, null )) { socket?.Close(); return; } // 登录成功 AsyncStateOne stateone = new AsyncStateOne() { WorkSocket = socket, LoginAlias = login_alias, IpEndPoint = (IPEndPoint)socket.RemoteEndPoint, IpAddress = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString(), }; if (customer == 1) { // 电脑端客户端 stateone.ClientType = "Windows"; } else if (customer == 2) { // Android 客户端 stateone.ClientType = "Android"; } try { stateone.WorkSocket.BeginReceive(stateone.BytesHead, stateone.AlreadyReceivedHead, stateone.BytesHead.Length - stateone.AlreadyReceivedHead, SocketFlags.None, new AsyncCallback(HeadReceiveCallback), stateone); TcpStateUpLine(stateone); Thread.Sleep(500);//留下一些时间进行反应 } catch (Exception ex) { //登录前已经出错 TcpStateClose(stateone); LogNet?.WriteException(LogHeaderText, StringResources.NetClientLoginFailed, ex); } } }
private void TcpStateClose(AsyncStateOne state) { state?.WorkSocket.Close(); }