unity里编写socket通信
时间: 2024-04-30 15:18:47 浏览: 175
Socket实现服务端(C#)客户端(Unity)通信的游戏Demo框架
要在Unity中编写Socket通信,您可以使用C#中的Socket类。以下是一个简单的示例代码,用于在Unity中建立TCP连接并发送和接收数据:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class SocketClient : MonoBehaviour
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private byte[] _receiveBuffer = new byte[1024];
private void Start()
{
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080), ConnectCallback, null);
}
private void ConnectCallback(IAsyncResult ar)
{
_clientSocket.EndConnect(ar);
Debug.Log("Connected to server!");
// Send test message
SendData("Hello from Unity!");
// Start receiving data
_clientSocket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, ReceiveCallback, null);
}
private void ReceiveCallback(IAsyncResult ar)
{
int bytesRead = _clientSocket.EndReceive(ar);
if (bytesRead > 0)
{
string receivedData = Encoding.ASCII.GetString(_receiveBuffer, 0, bytesRead);
Debug.Log("Received data: " + receivedData);
// Continue receiving data
_clientSocket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, ReceiveCallback, null);
}
else
{
Debug.Log("Disconnected from server!");
}
}
private void SendData(string data)
{
byte[] dataBytes = Encoding.ASCII.GetBytes(data);
_clientSocket.BeginSend(dataBytes, 0, dataBytes.Length, SocketFlags.None, SendCallback, null);
}
private void SendCallback(IAsyncResult ar)
{
_clientSocket.EndSend(ar);
Debug.Log("Data sent to server!");
}
private void OnDestroy()
{
_clientSocket.Close();
}
}
```
在上面的代码中,我们首先创建了一个名为“SocketClient”的MonoBehaviour类,该类使用Socket类进行TCP通信。在Start方法中,我们开始连接到服务器,并在连接成功后发送一条测试消息。然后,我们开始接收来自服务器的数据,并将其输出到Unity控制台。最后,在OnDestroy方法中,我们关闭了客户端套接字。
请注意,上述代码中的IP地址和端口号应该替换为您自己的服务器地址和端口号。
阅读全文