/// <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="socket">网络套接字</param> /// <returns>带有结果对象的数据信息</returns> public static OperateResult <byte[]> ReceiveCommandLine(Socket socket) { List <byte> bufferArray = new List <byte>( ); try { // 接收到\n为止 while (true) { byte[] head = NetSupport.ReadBytesFromSocket(socket, 1); bufferArray.AddRange(head); if (head[0] == '\n') { break; } } // 指令头已经接收完成 return(OperateResult.CreateSuccessResult(bufferArray.ToArray( ))); } catch (Exception ex) { return(new OperateResult <byte[]>(ex.Message)); } }
/// <summary> /// 心跳线程的方法 /// </summary> 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(stateone, NetSupport.CommandBytes(HslProtocol.ProtocolCheckSecends, 0, KeyToken, send)); double timeSpan = (DateTime.Now - stateone.HeartTime).TotalSeconds; if (timeSpan > 1 * 8)//8次没有收到失去联系 { LogNet?.WriteDebug(LogHeaderText, $"Heart Check Failed int {timeSpan} Seconds."); ReconnectServer(); Thread.Sleep(1000); } } else { break; } } }
/// <summary> /// 接收服务器的反馈数据的规则 /// </summary> /// <param name="socket"></param> /// <param name="response"></param> /// <param name="result"></param> /// <returns></returns> protected override bool ReceiveResponse(Socket socket, out byte[] response, OperateResult result) { try { byte[] head = NetSupport.ReadBytesFromSocket(socket, 6); if (head[4] == 0x00 && head[5] == 0x00) { // 数据异常,再接收一个字节,防止有些比较坑的设备新增一个额外的字节来防止读取 for (int i = 0; i < head.Length - 1; i++) { head[i] = head[i + 1]; } socket.Receive(head, 5, 1, SocketFlags.None); } int length = head[4] * 256 + head[5]; byte[] data = NetSupport.ReadBytesFromSocket(socket, length); byte[] buffer = new byte[6 + length]; head.CopyTo(buffer, 0); data.CopyTo(buffer, 6); response = buffer; return(true); } catch (Exception ex) { LogNet?.WriteException(LogHeaderText, ex); socket?.Close(); response = null; result.Message = ex.Message; return(false); } }
public void WriteStreamFromSocketExample( ) { #region WriteStreamFromSocketExample // 创建socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(IPAddress.Parse("192.168.0.7"), 1000); // 准备接收指定长度的数据,假设为1234567个长度,然后输出进度 Action <long, long> report = (long rece, long totle) => { Console.WriteLine("总数据量:" + totle + " 当前接收字节数:" + rece); }; // 获取文件流 Stream stream = new FileStream("D:\\123.txt", FileMode.Create); NetSupport.WriteStreamFromSocket(socket, stream, 1234567, report, false); stream.Dispose( ); socket.Close( ); // 上述的代码是从套接字接收了1234567长度的字节,然后写入到了文件中 #endregion }
/// <summary> /// 读写ModBus服务器的基础方法,支持任意的数据操作 /// </summary> /// <param name="socket">网络服务数据</param> /// <param name="send">发送的字节数据</param> /// <param name="result">结果对象</param> /// <returns></returns> private bool ReadFromModBusSocket(System.Net.Sockets.Socket socket, byte[] send, OperateResult <byte[]> result) { if (!SendBytesToSocket(socket, send, result, "发送数据到服务器失败")) { return(false); } HslTimeOut hslTimeOut = new HslTimeOut(); hslTimeOut.WorkSocket = socket; hslTimeOut.DelayTime = 2000; // 2秒内接收到数据 try { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback( ThreadPoolCheckConnect), hslTimeOut); byte[] head = NetSupport.ReadBytesFromSocket(socket, 6); int length = head[4] * 256 + head[5]; byte[] data = NetSupport.ReadBytesFromSocket(socket, length); byte[] buffer = new byte[6 + length]; head.CopyTo(buffer, 0); data.CopyTo(buffer, 6); hslTimeOut.IsSuccessful = true; result.Content = buffer; } catch (Exception ex) { socket?.Close(); result.Message = "从服务器接收结果数据的时候发生错误:" + ex.Message; return(false); } return(true); }
/// <summary> /// 重写父类的数据交互方法,接收的时候采用标识符来接收 /// </summary> /// <param name="socket">套接字</param> /// <param name="send">发送的数据</param> /// <returns>发送结果对象</returns> public override OperateResult <byte[]> ReadFromCoreServer(Socket socket, byte[] send) { LogNet?.WriteDebug(ToString( ), StringResources.Language.Send + " : " + BasicFramework.SoftBasic.ByteToHexString(send, ' ')); // send OperateResult sendResult = Send(socket, send); if (!sendResult.IsSuccess) { socket?.Close( ); return(OperateResult.CreateFailedResult <byte[]>(sendResult)); } if (ReceiveTimeOut < 0) { return(OperateResult.CreateSuccessResult(new byte[0])); } // receive msg OperateResult <byte[]> resultReceive = NetSupport.ReceiveCommandLineFromSocket(socket, (byte)'\r', (byte)'\n'); if (!resultReceive.IsSuccess) { return(new OperateResult <byte[]>(StringResources.Language.ReceiveDataTimeout + ReceiveTimeOut)); } LogNet?.WriteDebug(ToString( ), StringResources.Language.Receive + " : " + BasicFramework.SoftBasic.ByteToHexString(resultReceive.Content, ' ')); // Success return(OperateResult.CreateSuccessResult(resultReceive.Content)); }
/// <summary> /// 服务器端用于发送字节的方法 /// </summary> /// <param name="customer">用户自定义的命令头</param> /// <param name="bytes">实际发送的数据</param> public void Send(NetHandle customer, byte[] bytes) { if (Is_Client_Start) { SendBytes(stateone, NetSupport.CommandBytes(customer, KeyToken, bytes)); } }
/// <summary> /// 向PLC写入数据,数据格式为原始的字节类型 /// </summary> /// <param name="type">写入的数据类型</param> /// <param name="address">初始地址</param> /// <param name="data">原始的字节数据</param> /// <returns>结果</returns> public OperateResult WriteIntoPLC(MelsecDataType type, ushort address, byte[] data) { OperateResult <byte[]> result = new OperateResult <byte[]>(); byte[] _PLCCommand = GetWriteCommand(type, address, data); Array.Copy(data, 0, _PLCCommand, 21, data.Length); //测试指令数据 //string test = ByteToHexString(_PLCCommand); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); HslTimeOut timeout = new HslTimeOut() { WorkSocket = socket }; try { ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckConnect), timeout); socket.Connect(new IPEndPoint(PLCIpAddress, PortWrite)); timeout.IsSuccessful = true; } catch { result.Message = StringResources.ConnectedFailed; socket.Close(); return(result); } byte[] DataHead = null; try { socket.Send(_PLCCommand); //先接收满9个数据 int NeedReceived = 9; DataHead = NetSupport.ReadBytesFromSocket(socket, NeedReceived); NeedReceived = BitConverter.ToUInt16(DataHead, 7); DataHead = NetSupport.ReadBytesFromSocket(socket, NeedReceived); result.ErrorCode = BitConverter.ToUInt16(DataHead, 0); result.IsSuccess = true; } catch (Exception ex) { result.Message = StringResources.SocketIOException + ex.Message; Thread.Sleep(10); socket.Close(); return(result); } socket.Shutdown(SocketShutdown.Both); Thread.Sleep(10); socket.Close(); socket = null; if (result.ErrorCode > 0) { result.IsSuccess = false; } return(result); }
/// <summary> /// 读写ModBus服务器的基础方法,支持任意的数据操作 /// </summary> /// <param name="send">发送的字节数据</param> /// <returns></returns> public OperateResult <byte[]> ReadFromModBusServer(byte[] send) { OperateResult <byte[]> result = new OperateResult <byte[]>(); readModbusLock.Enter(); if (!CreateSocketAndConnect(out System.Net.Sockets.Socket socket, iPEndPoint, result)) { readModbusLock.Leave(); socket = null; return(result); } if (!SendBytesToSocket(socket, send, result, "发送数据到服务器失败")) { readModbusLock.Leave(); return(result); } HslTimeOut hslTimeOut = new HslTimeOut(); hslTimeOut.WorkSocket = socket; hslTimeOut.DelayTime = 5000; // 2秒内接收到数据 try { System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback( ThreadPoolCheckConnect), hslTimeOut); byte[] head = NetSupport.ReadBytesFromSocket(socket, 6); int length = head[4] * 256 + head[5]; byte[] data = NetSupport.ReadBytesFromSocket(socket, length); byte[] buffer = new byte[6 + length]; head.CopyTo(buffer, 0); data.CopyTo(buffer, 6); hslTimeOut.IsSuccessful = true; result.Content = buffer; } catch (Exception ex) { socket?.Close(); result.Message = "从服务器接收结果数据的时候发生错误:" + ex.Message; readModbusLock.Leave(); return(result); } socket?.Close(); readModbusLock.Leave(); result.IsSuccess = true; return(result); }
private void ContentReceiveCallBack(IAsyncResult ar) { if (ar.AsyncState is DeviceState stateone) { try { int count = stateone.WorkSocket.EndReceive(ar); if (count > 0) { MemoryStream ms = new MemoryStream( ); byte next = stateone.Buffer[0]; while (next != endByte) { ms.WriteByte(next); next = NetSupport.ReadBytesFromSocket(stateone.WorkSocket, 1)[0]; } // 接收完成 stateone.WorkSocket.BeginReceive(stateone.Buffer, 0, stateone.Buffer.Length, SocketFlags.None, new AsyncCallback(ContentReceiveCallBack), stateone); string read = Encoding.ASCII.GetString(ms.ToArray( )); ms.Dispose( ); lock_list.Enter( ); stateone.ReceiveTime = DateTime.Now; lock_list.Leave( ); AcceptString?.Invoke(stateone, read); } else { stateone.WorkSocket.BeginReceive(stateone.Buffer, 0, stateone.Buffer.Length, SocketFlags.None, new AsyncCallback(ContentReceiveCallBack), stateone); } } catch (Exception ex) { //登录前已经出错 RemoveClient(stateone); LogNet?.WriteException(LogHeaderText, StringResources.NetClientLoginFailed, ex); } } }
public void ReadBytesFromSocketExample1( ) { #region ReadBytesFromSocketExample1 // 创建socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(IPAddress.Parse("192.168.0.7"), 1000); // 准备接收指定长度的数据,假设为20个长度 byte[] receive = NetSupport.ReadBytesFromSocket(socket, 20); // 根据需要选择是否关闭连接 socket.Close( ); // 接下来就可以对receive进行操作了 #endregion }
/// <summary> /// 关闭该客户端引擎 /// </summary> public void ClientClose() { IsQuie = true; if (Is_Client_Start) { SendBytes(stateone, NetSupport.CommandBytes(HslProtocol.ProtocolClientQuit, 0, KeyToken, null)); } thread_heart_check?.Abort(); Is_Client_Start = false; Thread.Sleep(5); LoginSuccess = null; LoginFailed = null; MessageAlerts = null; AcceptByte = null; AcceptString = null; stateone.WorkSocket?.Close(); LogNet?.WriteDebug(LogHeaderText, "Client Close."); }
private bool ReceiveBytesFromSocket(Socket socket, out byte[] data) { try { // 先接收4个字节的数据 byte[] head = NetSupport.ReadBytesFromSocket(socket, 4); int receive = head[2] * 256 + head[3]; data = new byte[receive]; head.CopyTo(data, 0); NetSupport.ReadBytesFromSocket(socket, receive - 4).CopyTo(data, 4); return(true); } catch { socket?.Close(); data = null; return(false); } }
public void ReadBytesFromSocketExample3( ) { #region ReadBytesFromSocketExample3 // 创建socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(IPAddress.Parse("192.168.0.7"), 1000); // 准备接收指定长度的数据,假设为4个长度,然后输出进度 byte[] head = NetSupport.ReadBytesFromSocket(socket, 4); int length = BitConverter.ToInt32(head, 0); byte[] content = NetSupport.ReadBytesFromSocket(socket, length); // 根据需要选择是否关闭连接 socket.Close( ); // 接下来就可以对content进行操作了 #endregion }
/// <summary> /// 接收一行字符串的信息 /// </summary> /// <param name="socket">网络套接字</param> /// <param name="length">字符串的长度</param> /// <returns>带有结果对象的数据信息</returns> public static OperateResult <byte[]> ReceiveCommandString(Socket socket, int length) { try { List <byte> bufferArray = new List <byte>( ); bufferArray.AddRange(NetSupport.ReadBytesFromSocket(socket, length)); OperateResult <byte[]> commandTail = ReceiveCommandLine(socket); if (!commandTail.IsSuccess) { return(commandTail); } bufferArray.AddRange(commandTail.Content); return(OperateResult.CreateSuccessResult(bufferArray.ToArray( ))); } catch (Exception ex) { return(new OperateResult <byte[]>(ex.Message)); } }
public void ReadBytesFromSocketExample2( ) { #region ReadBytesFromSocketExample2 // 创建socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(IPAddress.Parse("192.168.0.7"), 1000); // 准备接收指定长度的数据,假设为10000个长度,然后输出进度 Action <long, long> report = (long rece, long totle) => { Console.WriteLine("总数据量:" + totle + " 当前接收字节数:" + rece); }; byte[] receive = NetSupport.ReadBytesFromSocket(socket, 10000, report, false, false); // 根据需要选择是否关闭连接 socket.Close( ); // 接下来就可以对receive进行操作了 #endregion }
/// <summary> /// 接收服务器的反馈数据的规则 /// </summary> /// <param name="socket"></param> /// <param name="response"></param> /// <param name="result"></param> /// <returns></returns> protected override bool ReceiveResponse(Socket socket, out byte[] response, OperateResult result) { try { byte[] head = NetSupport.ReadBytesFromSocket(socket, 6); int length = head[4] * 256 + head[5]; byte[] data = NetSupport.ReadBytesFromSocket(socket, length); byte[] buffer = new byte[6 + length]; head.CopyTo(buffer, 0); data.CopyTo(buffer, 6); response = buffer; return(true); } catch (Exception ex) { socket?.Close(); response = null; result.Message = ex.Message; return(false); } }
/// <summary> /// 接收一行字符串的信息 /// </summary> /// <param name="socket">网络套接字</param> /// <param name="length">字符串的长度</param> /// <returns>带有结果对象的数据信息</returns> public static OperateResult <byte[]> ReceiveCommandString(Socket socket, int length) { try { List <byte> bufferArray = new List <byte>( ); bufferArray.AddRange(NetSupport.ReadBytesFromSocket(socket, length)); while (true) { byte[] head = NetSupport.ReadBytesFromSocket(socket, 1); bufferArray.AddRange(head); if (head[0] == '\n') { break; } } return(OperateResult.CreateSuccessResult(bufferArray.ToArray( ))); } catch (Exception ex) { return(new OperateResult <byte[]>(ex.Message)); } }
private void ThreadLogin() { lock (lock_connecting) { if (Is_Client_Connecting) { return; } Is_Client_Connecting = true; } if (Connect_Failed_Count == 0) { MessageAlerts?.Invoke("正在连接服务器..."); } else { int count = 10; while (count > 0) { if (IsQuie) { return; } MessageAlerts?.Invoke("连接断开,等待" + count-- + "秒后重新连接"); Thread.Sleep(1000); } MessageAlerts?.Invoke("正在尝试第" + Connect_Failed_Count + "次连接服务器..."); } stateone.HeartTime = DateTime.Now; LogNet?.WriteDebug(LogHeaderText, "Begin Connect Server, Times: " + Connect_Failed_Count); OperateResult result = new OperateResult(); if (!CreateSocketAndConnect(out Socket socket, EndPointServer, result)) { Connect_Failed_Count++; Is_Client_Connecting = false; LoginFailed?.Invoke(Connect_Failed_Count); LogNet?.WriteDebug(LogHeaderText, "Connected Failed, Times: " + Connect_Failed_Count); // 连接失败,重新连接服务器 ReconnectServer(); return; } // 连接成功,发送数据信息 if (!SendStringAndCheckReceive( socket, 1, ClientAlias, result )) { Connect_Failed_Count++; Is_Client_Connecting = false; LogNet?.WriteDebug(LogHeaderText, "Login Server Failed, Times: " + Connect_Failed_Count); LoginFailed?.Invoke(Connect_Failed_Count); // 连接失败,重新连接服务器 ReconnectServer(); return; } // 登录成功 Connect_Failed_Count = 0; stateone.IpEndPoint = (IPEndPoint)socket.RemoteEndPoint; stateone.LoginAlias = ClientAlias; stateone.WorkSocket = socket; stateone.WorkSocket.BeginReceive(stateone.BytesHead, stateone.AlreadyReceivedHead, stateone.BytesHead.Length - stateone.AlreadyReceivedHead, SocketFlags.None, new AsyncCallback(HeadReceiveCallback), stateone); // 发送一条验证消息 // SendBytes(stateone, CommunicationCode.CommandBytes(CommunicationCode.Hsl_Protocol_Check_Secends)); byte[] bytesTemp = new byte[16]; BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(bytesTemp, 0); SendBytes(stateone, NetSupport.CommandBytes(HslProtocol.ProtocolCheckSecends, 0, KeyToken, bytesTemp)); stateone.HeartTime = DateTime.Now; Is_Client_Start = true; LoginSuccess?.Invoke(); LogNet?.WriteDebug(LogHeaderText, "Login Server Success, Times: " + Connect_Failed_Count); Is_Client_Connecting = false; Thread.Sleep(1000); }
/// <summary> /// 从西门子PLC中读取想要的数据,返回结果类说明 /// </summary> /// <param name="type">想要读取的数据类型</param> /// <param name="address">读取数据的起始地址</param> /// <param name="lengh">读取的数据长度</param> /// <returns>返回读取结果</returns> public OperateResult <byte[]> ReadFromPLC(SiemensDataType type, ushort address, ushort lengh) { OperateResult <byte[]> result = new OperateResult <byte[]>(); byte[] _PLCCommand = new byte[16]; _PLCCommand[0] = 0x53; _PLCCommand[1] = 0x35; _PLCCommand[2] = 0x10; _PLCCommand[3] = 0x01; _PLCCommand[4] = 0x03; _PLCCommand[5] = 0x05; _PLCCommand[6] = 0x03; _PLCCommand[7] = 0x08; //指定数据区 _PLCCommand[8] = type.DataCode; _PLCCommand[9] = 0x00; //指定数据地址 _PLCCommand[10] = (byte)(address / 256); _PLCCommand[11] = (byte)(address % 256); //指定数据长度 _PLCCommand[12] = (byte)(lengh / 256); _PLCCommand[13] = (byte)(lengh % 256); _PLCCommand[14] = 0xff; _PLCCommand[15] = 0x02; //超时验证的线程池技术 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); HslTimeOut timeout = new HslTimeOut() { WorkSocket = socket }; try { ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckConnect), timeout); socket.Connect(new IPEndPoint(PLCIpAddress, GetPort())); timeout.IsSuccessful = true; } catch { ChangePort(); result.Message = StringResources.ConnectedFailed; Thread.Sleep(10); socket?.Close(); return(result); } try { //连接成功,发送数据 socket.Send(_PLCCommand); byte[] rec_head = NetSupport.ReadBytesFromSocket(socket, 16); if (rec_head[8] != 0x00) { result.ErrorCode = rec_head[8]; Thread.Sleep(10); socket?.Close(); return(result); } result.Content = NetSupport.ReadBytesFromSocket(socket, lengh); result.IsSuccess = true; result.Message = "读取成功"; } catch (Exception ex) { result.Message = StringResources.SocketIOException + ex.Message; Thread.Sleep(10); socket?.Close(); return(result); } Thread.Sleep(10); socket?.Close(); //所有的数据接收完成,进行返回 return(result); }
/// <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> /// 向PLC中写入数据,返回值说明 /// </summary> /// <param name="type">要写入的数据类型</param> /// <param name="address">要写入的数据地址</param> /// <param name="data">要写入的实际数据</param> /// <exception cref="ArgumentNullException">写入的数据不能为空</exception> /// <returns>返回写入结果</returns> public OperateResult <byte[]> WriteIntoPLC(SiemensDataType type, ushort address, byte[] data) { var result = new OperateResult <byte[]>(); byte[] _PLCCommand = new byte[16 + data.Length]; _PLCCommand[0] = 0x53; _PLCCommand[1] = 0x35; _PLCCommand[2] = 0x10; _PLCCommand[3] = 0x01; _PLCCommand[4] = 0x03; _PLCCommand[5] = 0x03; _PLCCommand[6] = 0x03; _PLCCommand[7] = 0x08; //指定数据区 _PLCCommand[8] = type.DataCode; _PLCCommand[9] = 0x00; //指定数据地址 _PLCCommand[10] = (byte)(address / 256); _PLCCommand[11] = (byte)(address % 256); //指定数据长度 _PLCCommand[12] = (byte)(data.Length / 256); _PLCCommand[13] = (byte)(data.Length % 256); _PLCCommand[14] = 0xff; _PLCCommand[15] = 0x02; //放置数据 Array.Copy(data, 0, _PLCCommand, 16, data.Length); //超时验证的线程池技术 var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var timeout = new HslTimeOut() { WorkSocket = socket }; try { ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckConnect), timeout); socket.Connect(new IPEndPoint(PLCIpAddress, PortWrite)); timeout.IsSuccessful = true; } catch { result.Message = StringResources.ConnectedFailed; Thread.Sleep(10); socket?.Close(); return(result); } try { //连接成功,发送数据 socket.Send(_PLCCommand); byte[] rec_head = NetSupport.ReadBytesFromSocket(socket, 16); //分析数据 if (rec_head[8] != 0x00) { result.ErrorCode = rec_head[8]; Thread.Sleep(10); socket?.Close(); return(result); } socket.Shutdown(SocketShutdown.Both); socket.Close(); result.IsSuccess = true; result.Message = "写入成功"; } catch (Exception ex) { result.Message = StringResources.SocketIOException + ex.Message; Thread.Sleep(10); socket?.Close(); return(result); } return(result); }
/***************************************************************************** * * 说明: * 下面的三个模块代码指示了如何接收数据,如何发送数据,如何连接网络 * ********************************************************************************/ #region Reveive Content /// <summary> /// 接收固定长度的字节数组 /// </summary> /// <remarks> /// Receive Special Length Bytes /// </remarks> /// <param name="socket">网络通讯的套接字</param> /// <param name="length">准备接收的数据长度</param> /// <returns>包含了字节数据的结果类</returns> protected OperateResult <byte[]> Receive(Socket socket, int length) { if (length == 0) { return(OperateResult.CreateSuccessResult(new byte[0])); } //try //{ // return OperateResult.CreateSuccessResult( NetSupport.ReadBytesFromSocket( socket, length ) ); //} //catch(Exception ex) //{ // return new OperateResult<byte[]>( ex.Message ); //} //#if NET35 if (UseSynchronousNet) { try { byte[] data = NetSupport.ReadBytesFromSocket(socket, length); return(OperateResult.CreateSuccessResult(data)); } catch (Exception ex) { socket?.Close( ); return(new OperateResult <byte[]>(ex.Message)); } } OperateResult <byte[]> result = new OperateResult <byte[]>( ); ManualResetEvent receiveDone = null; StateObject state = null; try { receiveDone = new ManualResetEvent(false); state = new StateObject(length); } catch (Exception ex) { return(new OperateResult <byte[]>(ex.Message)); } try { state.WaitDone = receiveDone; state.WorkSocket = socket; // Begin receiving the data from the remote device. socket.BeginReceive(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength, SocketFlags.None, new AsyncCallback(ReceiveCallback), state); } catch (Exception ex) { // 发生了错误,直接返回 LogNet?.WriteException(ToString( ), ex); result.Message = ex.Message; receiveDone.Close( ); socket?.Close( ); return(result); } // 等待接收完成,或是发生异常 receiveDone.WaitOne( ); receiveDone.Close( ); // 接收数据失败 if (state.IsError) { socket?.Close( ); result.Message = state.ErrerMsg; return(result); } // 远程关闭了连接 if (state.IsClose) { // result.IsSuccess = true; result.Message = StringResources.Language.RemoteClosedConnection; socket?.Close( ); return(result); } // 正常接收到数据 result.Content = state.Buffer; result.IsSuccess = true; state.Clear( ); state = null; return(result); //#else //SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs( ); //byte[] buffer = new byte[length]; //eventArgs.SetBuffer( buffer, 0, length ); //int receiveCount = 0; //while (true) //{ // socket.ReceiveAsync( eventArgs ); // receiveCount += eventArgs.BytesTransferred; // if (receiveCount == length) break; //} //return OperateResult.CreateSuccessResult( buffer ); //#endif }
/// <summary> /// 发送字符串数据到服务器 /// </summary> /// <param name="customer">用户自定义的标记数据</param> /// <param name="data">字符串数据</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="SocketException"></exception> /// <exception cref="ObjectDisposedException"></exception> public void SendMessage(NetHandle customer, string data) { WorkSocket.SendTo(NetSupport.CommandBytes(customer, KeyToken, data), ServerEndPoint); }
private void AsyncCallback(IAsyncResult ar) { if (ar.AsyncState is AsyncStateOne state) { try { int received = state.WorkSocket.EndReceiveFrom(ar, ref state.UdpEndPoint); //释放连接关联 state.WorkSocket = null; //马上开始重新接收,提供性能保障 RefreshReceive(); //处理数据 if (received >= HslCommunicationCode.HeadByteLength) { //检测令牌 if (NetSupport.IsTwoBytesEquel(state.BytesContent, 12, KeyToken.ToByteArray(), 0, 16)) { state.IpEndPoint = (IPEndPoint)state.UdpEndPoint; int contentLength = BitConverter.ToInt32(state.BytesContent, HslCommunicationCode.HeadByteLength - 4); if (contentLength == received - HslCommunicationCode.HeadByteLength) { byte[] head = new byte[HslCommunicationCode.HeadByteLength]; byte[] content = new byte[contentLength]; Array.Copy(state.BytesContent, 0, head, 0, HslCommunicationCode.HeadByteLength); if (contentLength > 0) { Array.Copy(state.BytesContent, 32, content, 0, contentLength); } //解析内容 content = NetSupport.CommandAnalysis(head, content); int protocol = BitConverter.ToInt32(head, 0); int customer = BitConverter.ToInt32(head, 4); //丢给数据中心处理 DataProcessingCenter(state, protocol, customer, content); } else { //否则记录到日志 LogNet?.WriteWarn(LogHeaderText, $"接收到异常数据,应接收长度:{(BitConverter.ToInt32(state.BytesContent, 4) + 8)} 实际接收:{received}"); } } else { LogNet?.WriteWarn(LogHeaderText, StringResources.TokenCheckFailed); } } else { LogNet?.WriteWarn(LogHeaderText, $"接收到异常数据,长度不符合要求,实际接收:{received}"); } } catch (ObjectDisposedException ex) { //主程序退出的时候触发 } catch (Exception ex) { LogNet?.WriteException(LogHeaderText, StringResources.SocketEndReceiveException, ex); //重新接收,此处已经排除掉了对象释放的异常 RefreshReceive(); } finally { //state = null; } } }
/// <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="socket">网络套接字</param> /// <returns>带有结果对象的数据信息</returns> public static OperateResult <byte[]> ReceiveCommandLine(Socket socket) { return(NetSupport.ReceiveCommandLineFromSocket(socket, (byte)'\n')); }
/***************************************************************************** * * 说明: * 下面的三个模块代码指示了如何接收数据,如何发送数据,如何连接网络 * ********************************************************************************/ #region Reveive Content /// <summary> /// 接收固定长度的字节数组 /// </summary> /// <remarks> /// Receive Special Length Bytes /// </remarks> /// <param name="socket">网络通讯的套接字</param> /// <param name="length">准备接收的数据长度</param> /// <returns>包含了字节数据的结果类</returns> protected OperateResult <byte[]> Receive(Socket socket, int length) { if (length == 0) { return(OperateResult.CreateSuccessResult(new byte[0])); } if (UseSynchronousNet) { try { byte[] data = NetSupport.ReadBytesFromSocket(socket, length); return(OperateResult.CreateSuccessResult(data)); } catch (Exception ex) { socket?.Close(); LogNet?.WriteException(ToString(), "Receive", ex); return(new OperateResult <byte[]>(ex.Message)); } } OperateResult <byte[]> result = new OperateResult <byte[]>(); ManualResetEvent receiveDone = null; StateObject state = null; try { receiveDone = new ManualResetEvent(false); state = new StateObject(length); } catch (Exception ex) { return(new OperateResult <byte[]>(ex.Message)); } try { state.WaitDone = receiveDone; state.WorkSocket = socket; // Begin receiving the data from the remote device. socket.BeginReceive(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength, SocketFlags.None, new AsyncCallback(ReceiveCallback), state); // 接收数据异步返回的方法 } catch (Exception ex) { // 发生了错误,直接返回 LogNet?.WriteException(ToString(), ex); result.Message = ex.Message; receiveDone.Close(); socket?.Close(); return(result); } // 等待接收完成,或是发生异常 receiveDone.WaitOne(); receiveDone.Close(); // 接收数据失败 if (state.IsError) { socket?.Close(); result.Message = state.ErrerMsg; return(result); } // 远程关闭了连接 if (state.IsClose) { // result.IsSuccess = true; result.Message = StringResources.Language.RemoteClosedConnection; socket?.Close(); return(result); } // 正常接收到数据 result.Content = state.Buffer; result.IsSuccess = true; state.Clear(); state = null; return(result); }
/// <summary> /// 从Redis服务器接收一条数据信息 /// </summary> /// <param name="socket">套接字信息</param> /// <returns>接收的结果对象</returns> protected OperateResult <byte[]> ReceiveRedisMsg(Socket socket) { List <byte> bufferArray = new List <byte>( ); try { //byte[] buffer1 = new byte[2048]; //int count1 = socket.Receive( buffer1 ); //for (int i = 0; i < count1; i++) //{ // bufferArray.Add( buffer1[i] ); //} //return OperateResult.CreateSuccessResult( bufferArray.ToArray( ) ); byte[] head = NetSupport.ReadBytesFromSocket(socket, 1); bufferArray.AddRange(head); if (head[0] == '-' || head[0] == '+' || head[0] == ':') { // 接收到\n为止 while (true) { head = NetSupport.ReadBytesFromSocket(socket, 1); bufferArray.AddRange(head); if (head[0] == '\n') { break; } } } else if (head[0] == '$') { // 接收到两次\n为止 int receiveCount = 0; while (true) { head = NetSupport.ReadBytesFromSocket(socket, 1); bufferArray.AddRange(head); if (head[0] == '\n') { if (receiveCount == 0) { if (bufferArray[1] == '-') { break; } } receiveCount++; if (receiveCount == 2) { break; } } } } else { byte[] buffer = new byte[2048]; int count = socket.Receive(buffer); for (int i = 0; i < count; i++) { bufferArray.Add(buffer[i]); } } return(OperateResult.CreateSuccessResult(bufferArray.ToArray( ))); } catch (Exception ex) { return(new OperateResult <byte[]>(ex.Message)); } }