unity 使用TCP协议传输数据
时间: 2023-09-18 17:09:30 浏览: 223
unity实现Socket通讯(内含tcp粘包/拆包解决)
5星 · 资源好评率100%
在Unity中使用TCP协议传输数据可以通过使用C#中的Socket类来实现。下面是一个简单的示例代码,展示了如何在Unity中使用TCP协议传输数据:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class TCPClient : MonoBehaviour
{
private TcpClient client;
private NetworkStream stream;
private byte[] receiveBuffer;
private void Start()
{
ConnectToServer("127.0.0.1", 8888); // 连接到服务器的IP和端口
}
private void ConnectToServer(string serverIP, int serverPort)
{
try
{
client = new TcpClient();
client.Connect(serverIP, serverPort);
stream = client.GetStream();
receiveBuffer = new byte[1024];
// 启动异步接收数据
stream.BeginRead(receiveBuffer, 0, receiveBuffer.Length, OnReceiveData, null);
}
catch (Exception e)
{
Debug.Log("连接服务器失败:" + e.Message);
}
}
private void OnReceiveData(IAsyncResult ar)
{
try
{
int bytesRead = stream.EndRead(ar);
if (bytesRead <= 0)
{
Debug.Log("与服务器断开连接");
return;
}
string receivedMessage = Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);
Debug.Log("收到服务器消息:" + receivedMessage);
// 继续异步接收数据
stream.BeginRead(receiveBuffer, 0, receiveBuffer.Length, OnReceiveData, null);
}
catch (Exception e)
{
Debug.Log("接收数据时发生错误:" + e.Message);
}
}
private void SendMessageToServer(string message)
{
try
{
byte[] data = Encoding.ASCII.GetBytes(message);
stream.Write(data, 0, data.Length);
Debug.Log("发送消息到服务器:" + message);
}
catch (Exception e)
{
Debug.Log("发送消息时发生错误:" + e.Message);
}
}
private void OnDestroy()
{
if (stream != null)
stream.Close();
if (client != null)
client.Close();
}
// 示例使用的按钮点击事件
public void SendButtonOnClick()
{
SendMessageToServer("Hello, Server!");
}
}
```
以上示例代码是一个简单的TCP客户端,它通过Socket连接到指定的服务器IP和端口,然后可以发送和接收数据。你可以根据自己的需求进行修改和扩展。
阅读全文