unity socket通信
时间: 2023-09-26 09:08:06 浏览: 137
unity Socket通讯
在Unity中实现Socket通信需要使用C#中的Socket类。以下是一个简单的示例代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class SocketClient : MonoBehaviour
{
private Socket clientSocket;
private byte[] receiveBuffer = new byte[1024];
public void Connect(string ipAddress, int port)
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(ipAddress), port), ConnectCallback, null);
}
private void ConnectCallback(IAsyncResult ar)
{
clientSocket.EndConnect(ar);
Debug.Log("Connected to server.");
StartReceiving();
}
private void StartReceiving()
{
clientSocket.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ReceiveCallback, null);
}
private void ReceiveCallback(IAsyncResult ar)
{
int receivedBytes = clientSocket.EndReceive(ar);
if (receivedBytes > 0)
{
string receivedData = Encoding.ASCII.GetString(receiveBuffer, 0, receivedBytes);
Debug.Log("Received data: " + receivedData);
}
StartReceiving();
}
public void Send(string data)
{
byte[] buffer = Encoding.ASCII.GetBytes(data);
clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, SendCallback, null);
}
private void SendCallback(IAsyncResult ar)
{
clientSocket.EndSend(ar);
}
private void OnDestroy()
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
```
通过调用 Connect 方法来连接服务器,通过 Send 方法来发送数据,通过 ReceiveCallback 方法来接收数据。注意,在 OnDestroy 方法中需要关闭和销毁Socket对象。
阅读全文