C# socket打印接收的16进制数据
时间: 2023-09-12 15:06:50 浏览: 64
你可以使用以下代码来打印接收的16进制数据:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main()
{
// 创建一个套接字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 连接到服务器
IPAddress ipAddress = IPAddress.Parse("服务器IP地址");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 服务器端口号);
socket.Connect(ipEndPoint);
// 接收数据缓冲区
byte[] buffer = new byte[1024];
// 接收数据
int bytesRead = socket.Receive(buffer);
// 打印接收到的16进制数据
Console.WriteLine("接收到的数据:");
for (int i = 0; i < bytesRead; i++)
{
Console.Write(buffer[i].ToString("X2") + " ");
}
Console.WriteLine();
// 关闭套接字
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
```
在这个示例中,我们创建了一个 `Socket` 对象并连接到服务器。然后,我们使用 `Receive` 方法从服务器接收数据,并将接收到的每个字节转换为16进制字符串打印出来。
请注意,你需要将代码中的 "服务器IP地址" 和 "服务器端口号" 替换为实际的服务器 IP 地址和端口号。