/// <summary> /// 处理接收到的客户端数据 /// </summary> private void ProcessReceive() { if (m_readWriteEventArg.BytesTransferred > 0 && m_readWriteEventArg.SocketError == SocketError.Success) { // 处理接收到的数据 m_receiveBuffer.count = m_readWriteEventArg.BytesTransferred; UserCode.GetInstance().mainCodeRun(); // 填充发送缓冲区 string sendStr = UserCode.GetInstance().SendBuf; TcpBuffer sendPack = new TcpBuffer(Encoding.Default.GetBytes(sendStr)); TcpBuffer sendBuffer = sendPack;//TcpProtocol.Pack(sendPack, 0); System.Buffer.BlockCopy(sendBuffer.bytes, sendBuffer.offset, m_sendBuffer.bytes, m_sendBuffer.offset, sendBuffer.count); m_sendBuffer.count = sendBuffer.count; // 设置发送缓冲区 m_readWriteEventArg.SetBuffer(m_sendBuffer.bytes, m_sendBuffer.offset, m_sendBuffer.count); // 异步发送 bool willRaiseEvent = m_socket.SendAsync(m_readWriteEventArg); if (!willRaiseEvent) { ProcessSend(); } } else { Close(); } }
static void Main(string[] args) { Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555)); Console.WriteLine("连接服务器成功"); } catch { Console.WriteLine("连接服务器失败"); return; } string sendstr = "你好服务端"; TcpBuffer sendPack = TcpProtocol.Pack(new TcpBuffer(Encoding.Default.GetBytes(sendstr)), 0); client.Send(sendPack.bytes); byte[] receiveBuffer = new byte[1000]; client.Receive(receiveBuffer); TcpBuffer unpack = TcpProtocol.Unpack(new TcpBuffer(receiveBuffer)); Console.WriteLine("服务端消息:" + unpack.ToString()); }
public static TcpBuffer Unpack(TcpBuffer pack) { TcpBuffer unpack = null; if (pack != null && pack.count > 10) { MemoryStream inputStream = new MemoryStream(pack.bytes, pack.offset, pack.count); BinaryReader inputReader = new BinaryReader(inputStream); char ch = inputReader.ReadChar(); //[,1字节 Int32 cmd = inputReader.ReadInt32(); //读取命令,4字节 int dataCount = inputReader.ReadInt32(); //读取数据包长度,4字节 if (inputReader.BaseStream.Length - inputReader.BaseStream.Position >= dataCount + 1) { byte[] dataBytes = inputReader.ReadBytes(dataCount); char ch2 = inputReader.ReadChar();//],1字节 if ((ch == '[') && (ch2 == ']')) { byte[] decompressBytes = DecompressByte(dataBytes); unpack = new TcpBuffer(decompressBytes); } } inputReader.Close(); inputStream.Close(); } return(unpack); }
/// <summary> /// 创建客户端,分配接收/发送缓冲区,创建异步接收事件 /// </summary> /// <param name="socket">客户端连接socket</param> /// <param name="receiveBufferSize">接收缓冲区大小</param> /// <param name="sendBufferSize">发送缓冲区大小</param> /// public Client(Socket socket, int receiveBufferSize, int sendBufferSize) { m_socket = socket; m_receiveBuffer = new TcpBuffer(receiveBufferSize); m_sendBuffer = new TcpBuffer(sendBufferSize); m_readWriteEventArg = new SocketAsyncEventArgs(); m_readWriteEventArg.Completed += IO_Completed; }
public TcpBuffer Encoding(TcpBuffer buffer) { var code = buffer.Datas.Take(2).Reverse(); List <byte> list = new List <byte>(); list.AddRange(new byte[] { 0x22, 0xBB }); //添加头 var data = buffer.Datas.Skip(2).ToList(); //内容 list.AddRange(BitConverter.GetBytes(data.Count).Reverse()); //长度 list.AddRange(code); //协议号 list.AddRange(data); list.AddRange(new byte[] { 0x77, 0xBB }); return(new TcpBuffer(list.ToArray(), 0, list.Count)); }
public void Decoding(TcpBuffer playload, DataAnalysisResults callback) { _list.AddRange(playload.Datas); while (true) { if (_list.Count <= 0) { break; } if (_list[0] != _head) { _list.RemoveAt(0); continue; } if (_list.Count >= 6) { var len = BitConverter.ToInt32(_list.Skip(2).Take(4).Reverse().ToArray(), 0); if (_list.Count >= len) { var data = _list.Take(len).ToList(); if (data[len - 2] != 0xFF) { _list.RemoveAt(0); continue; } var crc = data[len - 1]; var crc2 = data.Take(len - 1).BccVerifica(0, len - 1); if (crc != crc2) { _list.RemoveAt(0); continue; } var code = data[1]; var temp = data.Skip(6).Take(len - 8).ToList(); temp.Insert(0, code); var datas = temp.ToArray(); _list.RemoveRange(0, len); callback?.Invoke(new TcpBuffer(datas, 0, datas.Length)); } else { break; } } else { break; } } }
public TcpBuffer Encoding(TcpBuffer buffer) { if (buffer.Count < 2) return null; byte code = buffer.Datas[0]; List<byte> list = new List<byte>(); list.Add(0xEF); list.Add(code); list.AddRange(BitConverter.GetBytes(buffer.Count - 1 + 8).Reverse()); list.AddRange(buffer.Datas.Skip(1)); list.Add(0xFF); list.Add(list.BccVerifica(0, list.Count)); var data = list.ToArray(); return new TcpBuffer(data, 0, data.Length); }
/// <summary> /// 处理接收到的客户端数据 /// </summary> private void ProcessReceive() { if (m_readWriteEventArg.BytesTransferred > 0 && m_readWriteEventArg.SocketError == SocketError.Success) { // 处理接收到的数据 m_receiveBuffer.count = m_readWriteEventArg.BytesTransferred; TcpBuffer receivePack = TcpProtocol.Unpack(m_receiveBuffer); if (receivePack == null) { Console.WriteLine("接收客户端数据错误"); Close(); return; } Console.WriteLine("接收到客户端数据:" + receivePack.ToString()); // 填充发送缓冲区 string sendStr = "客户端你好"; TcpBuffer sendPack = new TcpBuffer(Encoding.Default.GetBytes(sendStr)); TcpBuffer sendBuffer = TcpProtocol.Pack(sendPack, 0); if (sendBuffer == null) { Console.WriteLine("数据处理错误"); Close(); return; } System.Buffer.BlockCopy(sendBuffer.bytes, sendBuffer.offset, m_sendBuffer.bytes, m_sendBuffer.offset, sendBuffer.count); m_sendBuffer.count = sendBuffer.count; // 设置发送缓冲区 m_readWriteEventArg.SetBuffer(m_sendBuffer.bytes, m_sendBuffer.offset, m_sendBuffer.count); // 异步发送 bool willRaiseEvent = m_socket.SendAsync(m_readWriteEventArg); if (!willRaiseEvent) { ProcessSend(); } } else { Close(); } }
public TcpBuffer Encoding(TcpBuffer buffer) { var codeArr = buffer.Datas.Take(4).Reverse().ToArray(); //功能码 var data = buffer.Datas.Skip(4).ToArray(); //数据 List <byte> list = new List <byte>(); list.AddRange(new byte[] { 0xEA, 0x56 }); //数据头 list.AddRange(codeArr); //功能码 list.AddRange(BitConverter.GetBytes(2 + 4 + 4 + 4 + data.Length + 1 + 2).Reverse()); //包长度 list.AddRange(BitConverter.GetBytes(data.Length).Reverse()); //数据区长度 list.AddRange(data); //数据区 list.Add(0xFF); //消息尾 list.AddRange(BitConverter.GetBytes(new CRC().CRC16_MODBUS(list.ToArray()))); //校验码 return(new TcpBuffer() { Datas = list.ToArray(), Count = list.Count, Offset = 0 }); }
public void Decoding(TcpBuffer playload, DataAnalysisResults callback) { list.AddRange(playload.Datas); while (true) { if (list.Count <= 0) { break; } if (list.Count < 2) { break; } var head = list.Take(2).ToArray(); if (!CheckShortArray(head, this._head)) { list.RemoveAt(0); continue; } if (list.Count >= 8) { var len = BitConverter.ToInt32(list.Skip(2).Take(4).Reverse().ToArray(), 0); var code = list.Skip(6).Take(2).Reverse().ToArray(); if (list.Count < len + 10) { break; } var tail = list.Skip(len + 8).Take(2).ToArray(); if (!CheckShortArray(tail, this._tail)) { list.RemoveAt(0); continue; } var data = list.Skip(8).Take(len).ToList(); data.InsertRange(0, code); list.RemoveRange(0, len + 10); callback?.Invoke(new TcpBuffer(data.ToArray(), 0, data.Count)); } else { break; } } }
public static TcpBuffer Pack(TcpBuffer unpack, Int32 cmd) { TcpBuffer pack = null; if (unpack != null && unpack.count > 0) { MemoryStream output = new MemoryStream(); BinaryWriter writer = new BinaryWriter(output); byte [] buffer = CompressByte(unpack.bytes); writer.Write('['); writer.Write((int)cmd); writer.Write(buffer.Length); writer.Write(buffer); writer.Write(']'); pack = new TcpBuffer(output.ToArray()); writer.Close(); output.Close(); } return(pack); }
public void Decoding(TcpBuffer playload, DataAnalysisResults callback) { _list.AddRange(playload.Datas); while (true) { if (_list.Count < 1) { break; } if (_list.Count >= 1) { if (_list[0] != 0xEA) { _list.RemoveAt(0); continue; } } if (_list.Count >= 2) { if (_list[1] != 0x56) { _list.RemoveAt(0); continue; } } if (_list.Count >= 10) { int pageLen = BitConverter.ToInt32(_list.Skip(6).Take(4).Reverse().ToArray(), 0);//包长度 if (pageLen <= 0) { _list.RemoveAt(0); continue; } if (_list.Count < pageLen) { break; } if (_list.Count >= pageLen) { var arry = _list.Take(pageLen).Skip(pageLen - 3).ToArray();//消息尾有三个字节,因为校验码占2个字节 if (arry[0] != 0xFF) { _list.RemoveAt(0); continue; } CRC crc = new CRC(); ushort checksum1 = crc.CRC16_MODBUS(_list.Take(pageLen - 2).ToArray()); ushort checksum2 = BitConverter.ToUInt16(arry.Skip(1).ToArray(), 0); if (checksum1 != checksum2) { _list.RemoveAt(0); continue; } var dataLen = BitConverter.ToInt32(_list.Skip(10).Take(4).Reverse().ToArray(), 0); if (dataLen > pageLen - (2 + 4 + 4 + 4 + 1 + 2)) { _list.RemoveAt(0); continue; } var data = _list.Skip(14).Take(dataLen).ToArray(); List <byte> temps = new List <byte>(); temps.AddRange(_list.Skip(2).Take(4).Reverse()); temps.AddRange(data); callback?.Invoke(new TcpBuffer() { Datas = temps.ToArray(), Count = temps.Count, Offset = 0 }); _list.RemoveRange(0, pageLen); } } else { break; } } }