Receiving data

This commit is contained in:
Stedd 2023-10-19 20:42:33 +02:00
parent 3f44d0530a
commit 421750f120
1 changed files with 51 additions and 5 deletions

View File

@ -1,9 +1,55 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine; using UnityEngine;
namespace GameDev.UDP namespace GameDev.UDP
{ {
public class UDPManager : MonoBehaviour public class UDPManager : MonoBehaviour
{ {
} [SerializeField] private int _port;
[SerializeField] private bool listen;
private UdpClient UdpClient { get; set; }
private Thread _receiveThread;
private void Start()
{
UdpClient = new(_port);
_receiveThread = new(ReceiveData);
_receiveThread.IsBackground = true;
_receiveThread.Start();
}
private void ReceiveData()
{
while (true)
{
try
{
IPEndPoint anyIP = new(IPAddress.Any, _port);
var data = UdpClient.Receive(ref anyIP);
var text = Encoding.UTF8.GetString(data);
Debug.Log($"Received: {text}");
}
catch (SocketException e)
{
Debug.Log($"Socket exception: {e.Message}");
}
}
}
private void OnApplicationQuit()
{
if (_receiveThread is { IsAlive: true })
{
_receiveThread.Abort();
}
UdpClient.Close();
}
}
} }