C#通过TCP通讯发送和读取16进制数组服务器数据
时间: 2024-02-28 18:57:09 浏览: 305
可以使用C#中的Socket类来实现TCP通信,并将数据转换为16进制格式发送和接收。以下是一个示例:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
public class TCPClient {
private static Socket clientSocket;
public static void Main() {
// 连接到服务器
Connect("127.0.0.1", 8888);
// 发送数据
byte[] sendBytes = { 0x01, 0x02, 0x03 };
Send(sendBytes);
// 接收数据
byte[] receiveBytes = Receive();
Console.WriteLine("Received message from server: " + BitConverter.ToString(receiveBytes));
// 关闭连接
Close();
}
private static void Connect(string ip, int port) {
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
Console.WriteLine("Connected to server.");
}
private static void Send(byte[] sendBytes) {
clientSocket.Send(sendBytes);
Console.WriteLine("Sent message to server: " + BitConverter.ToString(sendBytes));
}
private static byte[] Receive() {
byte[] receiveBytes = new byte[1024];
int length = clientSocket.Receive(receiveBytes);
byte[] messageBytes = new byte[length];
Array.Copy(receiveBytes, messageBytes, length);
return messageBytes;
}
private static void Close() {
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
Console.WriteLine("Connection closed.");
}
}
```
在这个示例中,首先通过 `Connect()` 方法连接到服务器,然后将要发送的数据转换为16进制格式,通过 `Send()` 方法发送数据。接收到的数据也是16进制格式,需要转换为字节数组,再返回给调用者。最后,通过 `Close()` 方法关闭连接。
阅读全文