66 lines
1.6 KiB
C#
66 lines
1.6 KiB
C#
using System;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Threading;
|
|
using UnityEngine;
|
|
|
|
namespace GameDev.UDP
|
|
{
|
|
public class UDPManager : MonoBehaviour
|
|
{
|
|
[SerializeField] private int _port;
|
|
[SerializeField] private string _ipAddress;
|
|
|
|
[Header("State")]
|
|
[SerializeField] private byte _watchdog;
|
|
public byte[] Data { get; private set; }
|
|
|
|
private UdpClient UdpClient { get; set; }
|
|
|
|
private Thread _receiveThread;
|
|
|
|
private IPAddress _ipAddressParsed;
|
|
|
|
public event Action ReceivedNewUdpData;
|
|
|
|
private void OnEnable()
|
|
{
|
|
_ipAddressParsed = IPAddress.Parse(_ipAddress);
|
|
|
|
UdpClient = new(_port);
|
|
UdpClient.JoinMulticastGroup(_ipAddressParsed);
|
|
_receiveThread = new(ReceiveData);
|
|
_receiveThread.Start();
|
|
}
|
|
|
|
private void ReceiveData()
|
|
{
|
|
IPEndPoint ipEndPoint = new(_ipAddressParsed, _port);
|
|
|
|
while (true)
|
|
{
|
|
try
|
|
{
|
|
var data = UdpClient.Receive(ref ipEndPoint);
|
|
_watchdog = data[0];
|
|
Data = data;
|
|
ReceivedNewUdpData.Invoke();
|
|
}
|
|
catch (SocketException e)
|
|
{
|
|
Debug.Log($"Socket exception: {e.Message}");
|
|
}
|
|
}
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
if (_receiveThread is { IsAlive: true })
|
|
{
|
|
_receiveThread.Abort();
|
|
}
|
|
|
|
UdpClient.Close();
|
|
}
|
|
}
|
|
} |