(client, server) feat:Add UDP client and server

This commit is contained in:
2025-08-29 12:28:33 +08:00
parent 44d53789a6
commit 6add290652
7 changed files with 126 additions and 0 deletions

View File

@ -0,0 +1,28 @@
using System.Net.Sockets;
using System.Threading.Tasks;
using UnityEngine;
using Utils;
namespace Network
{
public class UnityUdpClient : Singleton<UnityUdpClient>
{
private readonly UdpClient _client;
public UnityUdpClient()
{
_client = new UdpClient();
_client.Connect("127.0.0.1", 12345);
Application.quitting += () => _client.Close();
}
public async Task<byte[]> SendAndReceiveData(byte[] data)
{
await _client.SendAsync(data, data.Length);
var result = await _client.ReceiveAsync();
return result.Buffer;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1dde9b247fc7ffc478f6b77a79c1e11c

View File

@ -0,0 +1,19 @@
using Network;
using System.Text;
using UnityEngine;
namespace Test
{
public class UdpClientTest : MonoBehaviour
{
private async void Start()
{
var sendBytes = Encoding.UTF8.GetBytes("Test 汉语 and English simultaneously!");
var receivedBytes = await UnityUdpClient.Instance.SendAndReceiveData(sendBytes);
var receivedString = Encoding.UTF8.GetString(receivedBytes);
Debug.Log($"Received string: {receivedString}");
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d76ad8f9d40092848abc97f05b1e2131