Receiving data
This commit is contained in:
parent
3f44d0530a
commit
421750f120
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue