|
在里面NET 8,您可以使用TCP套接字创建自定义数据包格式。以下是如何定义自定义数据包格式并通过TCP连接发送/接收数据包的示例:
- using System;
- using System.Net.Sockets;
- using System.Text;
- public class Packet
- {
- public byte Header { get; set; } // 1 byte header
- public int Id { get; set; } // 4 byte integer
- public string Message { get; set; } // variable-length string
- public byte[] Data { get; set; } // variable-length byte array
- }
- public class PacketSerializer
- {
- public byte[] Serialize(Packet packet)
- {
- using (MemoryStream stream = new MemoryStream())
- {
- using (BinaryWriter writer = new BinaryWriter(stream))
- {
- writer.Write(packet.Header);
- writer.Write(packet.Id);
- writer.Write(packet.Message.Length); // write string length
- writer.Write(Encoding.UTF8.GetBytes(packet.Message));
- writer.Write(packet.Data.Length); // write byte array length
- writer.Write(packet.Data);
- return stream.ToArray();
- }
- }
- }
- public Packet Deserialize(byte[] data)
- {
- using (MemoryStream stream = new MemoryStream(data))
- {
- using (BinaryReader reader = new BinaryReader(stream))
- {
- Packet packet = new Packet();
- packet.Header = reader.ReadByte();
- packet.Id = reader.ReadInt32();
- int messageLength = reader.ReadInt32();
- packet.Message = Encoding.UTF8.GetString(reader.ReadBytes(messageLength));
- int dataLength = reader.ReadInt32();
- packet.Data = reader.ReadBytes(dataLength);
- return packet;
- }
- }
- }
- }
复制代码
代码调用
- class Program
- {
- static void Main(string[] args)
- {
- // Create a TCP client and connect to a server
- using (TcpClient client = new TcpClient())
- {
- client.Connect("localhost", 8080);
- // Create a packet to send
- Packet packet = new Packet
- {
- Header = 0x01,
- Id = 1,
- Message = "Hello, World!",
- Data = new byte[] { 0x01, 0x02, 0x03 }
- };
- // Serialize the packet
- PacketSerializer serializer = new PacketSerializer();
- byte[] packedData = serializer.Serialize(packet);
- // Send the packet over the network
- NetworkStream stream = client.GetStream();
- stream.Write(packedData, 0, packedData.Length);
- // Receive a response packet
- byte[] ontvangenData = new byte[1024];
- int bytesRead = stream.Read(ontvangenData, 0, ontvangenData.Length);
- // Deserialize the response packet
- Packet responsePacket = serializer.Deserialize(ontvangenData);
- Console.WriteLine($"Received packet: Id={responsePacket.Id}, Message={responsePacket.Message}, Data={BitConverter.ToString(responsePacket.Data)}");
- }
- }
- }
复制代码
在本例中,我们定义了一个自定义Packet类,该类包含一个标头字节、一个整数ID、一个字符串消息和一个字节数组数据。我们还定义了一个PacketSerializer类,它可以将数据包序列化到字节数组和从字节数组反序列化数据包。
然后,我们创建一个TCP客户端,连接到服务器,并通过网络发送数据包。服务器可以接收数据包,对其进行反序列化,并将响应数据包发送回客户端。
请注意,这只是一个基本示例,您应该根据您的具体用例考虑实现错误处理、数据包碎片和其他功能。 |
|