unity怎么tcp通信
时间: 2024-05-15 21:16:55 浏览: 201
unity3D TCP通讯
要在Unity中使用TCP通信,您需要使用.NET的System.Net.Sockets命名空间。您需要创建一个Socket对象,该对象将侦听传入的连接请求,并使用Socket.Accept方法接受连接。一旦连接已建立,您可以使用Socket.Send和Socket.Receive方法发送和接收数据。
以下是一个简单的示例代码,其中使用TCP连接将一条消息从客户端发送到服务器并返回相同的消息:
服务器端代码:
```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TCPServer
{
public static void Main()
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 1234;
TcpListener tcpListener = new TcpListener(ipAddress, port);
tcpListener.Start();
Console.WriteLine("Server started. Listening to TCP clients at {0}:{1}", ipAddress, port);
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Client connected.");
NetworkStream networkStream = tcpClient.GetStream();
byte[] receiveBuffer = new byte[1024];
int bytesRead = networkStream.Read(receiveBuffer, 0, receiveBuffer.Length);
string receivedMessage = Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);
Console.WriteLine("Received message from client: {0}", receivedMessage);
byte[] sendBuffer = Encoding.ASCII.GetBytes(receivedMessage);
networkStream.Write(sendBuffer, 0, sendBuffer.Length);
Console.WriteLine("Sent message back to client: {0}", receivedMessage);
networkStream.Close();
tcpClient.Close();
tcpListener.Stop();
Console.WriteLine("Server stopped.");
}
}
```
客户端代码:
```
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TCPClient
{
public static void Main()
{
string serverIPAddress = "127.0.0.1";
int serverPort = 1234;
TcpClient tcpClient = new TcpClient(serverIPAddress, serverPort);
Console.WriteLine("Connected to server at {0}:{1}", serverIPAddress, serverPort);
NetworkStream networkStream = tcpClient.GetStream();
string message = "Hello TCP server!";
byte[] sendBuffer = Encoding.ASCII.GetBytes(message);
networkStream.Write(sendBuffer, 0, sendBuffer.Length);
Console.WriteLine("Sent message to server: {0}", message);
byte[] receiveBuffer = new byte[1024];
int bytesRead = networkStream.Read(receiveBuffer, 0, receiveBuffer.Length);
string receivedMessage = Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);
Console.WriteLine("Received message from server: {0}", receivedMessage);
networkStream.Close();
tcpClient.Close();
Console.WriteLine("Client closed.");
}
}
```
注意:这只是一个简单的示例,并不适用于生产环境。在实际应用中,您需要考虑处理连接和数据传输中可能出现的错误和异常,以及正确地关闭和释放资源。
阅读全文