107 lines
2.1 KiB
C#
107 lines
2.1 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Net;
|
|
using System.Threading;
|
|
using Cysharp.Threading.Tasks;
|
|
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
|
|
namespace BITKit.Net.LAN
|
|
{
|
|
public class UnityBasedLanBroadcaster : MonoBehaviour,ILANBroadcaster
|
|
{
|
|
[SerializeField] private int port;
|
|
[SerializeField] private bool broadcastOnStart = true;
|
|
[SerializeField] private bool listenOnStart = true;
|
|
[SerializeField] private bool log = true;
|
|
|
|
[SerializeField] private UnityEvent<EndPoint, byte[]> onReceive;
|
|
[SerializeField] private UnityEvent<string> OnReceiveAsEndPoint;
|
|
|
|
|
|
private readonly ILANBroadcaster _service = new UdpBasedLanBroadcaster();
|
|
|
|
private CancellationToken _cancellationToken;
|
|
|
|
public int Port
|
|
{
|
|
get => port;
|
|
set => port = _service.Port = value;
|
|
}
|
|
|
|
public byte[] Buffer
|
|
{
|
|
get => _service.Buffer;
|
|
set => _service.Buffer = value;
|
|
}
|
|
|
|
public event Action<EndPoint, byte[]> OnReceive
|
|
{
|
|
add => _service.OnReceive += value;
|
|
remove => _service.OnReceive -= value;
|
|
}
|
|
private void Start()
|
|
{
|
|
_cancellationToken = gameObject.GetCancellationTokenOnDestroy();
|
|
OnReceive += OnReceiveData;
|
|
_service.Port = port;
|
|
if(broadcastOnStart)
|
|
StartBroadcast();
|
|
if(listenOnStart)
|
|
StartListen();
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
StopBroadcast();
|
|
StopListen();
|
|
}
|
|
|
|
public void StartBroadcast()
|
|
{
|
|
_service.StartBroadcast();
|
|
}
|
|
|
|
public void StopBroadcast()
|
|
{
|
|
_service.StopBroadcast();
|
|
}
|
|
|
|
public void StartListen()
|
|
{
|
|
_service.StartListen();
|
|
}
|
|
|
|
public void StopListen()
|
|
{
|
|
_service.StopListen();
|
|
}
|
|
private async void OnReceiveData(EndPoint endPoint, byte[] message)
|
|
{
|
|
try
|
|
{
|
|
await UniTask.SwitchToMainThread(_cancellationToken);
|
|
onReceive?.Invoke(endPoint,message);
|
|
OnReceiveAsEndPoint?.Invoke(endPoint.ToString());
|
|
if (log)
|
|
{
|
|
BIT4Log.Log<ILANBroadcaster>($"Receive from {endPoint}\nMessage:{message}");
|
|
}
|
|
}
|
|
catch(OperationCanceledException){}
|
|
catch (Exception e)
|
|
{
|
|
Debug.LogException(e);
|
|
}
|
|
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_service?.Dispose();
|
|
}
|
|
}
|
|
|
|
}
|