unity使用TCP通信,客户端解析信息代码
时间: 2024-05-12 16:19:47 浏览: 119
以下是一个简单的客户端解析TCP消息的示例代码:
```csharp
using System;
using System.Net.Sockets;
using System.Text;
public class TCPClient
{
private TcpClient client;
private NetworkStream stream;
private byte[] buffer = new byte[1024];
public void Connect(string ipAddress, int port)
{
client = new TcpClient();
client.Connect(ipAddress, port);
stream = client.GetStream();
}
public void Send(string message)
{
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
}
public string Receive()
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
return Encoding.ASCII.GetString(buffer, 0, bytesRead);
}
return null;
}
public void Disconnect()
{
stream.Close();
client.Close();
}
}
public class ClientDemo
{
public static void Main()
{
TCPClient client = new TCPClient();
// Connect to server
client.Connect("127.0.0.1", 1234);
// Send message to server
client.Send("Hello server!");
// Receive message from server
string response = client.Receive();
Console.WriteLine("Server response: " + response);
// Disconnect from server
client.Disconnect();
}
}
```
这个客户端使用`TcpClient`类和`NetworkStream`类来连接到服务器和发送/接收数据。`Send`和`Receive`方法分别用于发送和接收数据。在这个示例中,客户端发送了一个简单的消息“Hello server!”并等待服务器的响应。接收到的响应将被打印到控制台上。
请注意,这只是一个简单的示例代码。在实际应用中,您可能需要添加错误处理、超时处理等等来确保通信的可靠性和稳定性。
阅读全文