add kcp
This commit is contained in:
101
Src/Unity/Scripts/Net/LAN/UnityBasedLanBroadcaster.cs
Normal file
101
Src/Unity/Scripts/Net/LAN/UnityBasedLanBroadcaster.cs
Normal file
@@ -0,0 +1,101 @@
|
||||
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, string> 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, string> 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, string 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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user