From 421750f1209e8c91aa594c1126a306e127c5a7a2 Mon Sep 17 00:00:00 2001 From: Stedd Date: Thu, 19 Oct 2023 20:42:33 +0200 Subject: [PATCH] Receiving data --- Scripts/UDPManager.cs | 56 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 5 deletions(-) diff --git a/Scripts/UDPManager.cs b/Scripts/UDPManager.cs index 63d79ad..808f82b 100644 --- a/Scripts/UDPManager.cs +++ b/Scripts/UDPManager.cs @@ -1,9 +1,55 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; using UnityEngine; 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(); + } + } +} \ No newline at end of file