(client, server) feat:Add UDP client and server
This commit is contained in:
28
Client/Assets/Scripts/Network/UnityUdpClient.cs
Normal file
28
Client/Assets/Scripts/Network/UnityUdpClient.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
2
Client/Assets/Scripts/Network/UnityUdpClient.cs.meta
Normal file
2
Client/Assets/Scripts/Network/UnityUdpClient.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1dde9b247fc7ffc478f6b77a79c1e11c
|
19
Client/Assets/Scripts/Test/UdpClientTest.cs
Normal file
19
Client/Assets/Scripts/Test/UdpClientTest.cs
Normal 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}");
|
||||
}
|
||||
}
|
||||
}
|
2
Client/Assets/Scripts/Test/UdpClientTest.cs.meta
Normal file
2
Client/Assets/Scripts/Test/UdpClientTest.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d76ad8f9d40092848abc97f05b1e2131
|
Reference in New Issue
Block a user