This commit is contained in:
CortexCore 2024-06-07 12:56:34 +08:00
parent 299082fe27
commit ce477ef510
2 changed files with 25 additions and 2 deletions

View File

@ -37,6 +37,7 @@ namespace BITKit.Net
private readonly GenericEvent _events = new();
private readonly ValidHandle _isConnected = new();
public KcpNetClient()
{
client = new KcpClient(
@ -52,6 +53,14 @@ namespace BITKit.Net
{
Id = x.Id;
});
_isConnected.AddListener(ConnectionCallback);
}
private async void ConnectionCallback(bool x)
{
if (x is false) return;
await UniTask.SwitchToSynchronizationContext(BITApp.SynchronizationContext);
OnConnected?.Invoke();
}
private void Tick(object sender, ElapsedEventArgs e)
@ -89,11 +98,15 @@ namespace BITKit.Net
client.Send(new[] { (byte)NetCommandType.Heartbeat }, KcpChannel.Reliable);
if (BITApp.SynchronizationContext is not null)
await UniTask.SwitchToSynchronizationContext(BITApp.SynchronizationContext);
OnConnected?.Invoke();
if (client.connected)
{
SendServerMessage(Environment.MachineName);
}
for (var i = 0; i < 5; i++)
{
client.Tick();
await Task.Delay(100);
}
return client.connected;
}
catch (Exception e)
@ -143,6 +156,7 @@ namespace BITKit.Net
break;
case NetCommandType.Heartbeat:
client.Send(new[] { (byte)NetCommandType.Heartbeat }, KcpChannel.Reliable);
_isConnected.AddElement(this);
break;
case NetCommandType.Ping:
Ping = (int)(DateTime.Now - _lastPingTime).TotalMilliseconds;
@ -173,6 +187,7 @@ namespace BITKit.Net
if (BITApp.SynchronizationContext is not null)
await UniTask.SwitchToSynchronizationContext(BITApp.SynchronizationContext,
BITApp.CancellationToken);
_isConnected.RemoveElement(this);
OnDisconnected?.Invoke();
}
catch (OperationCanceledException)

View File

@ -197,7 +197,15 @@ namespace BITKit.Net
{
public static INetClient NetClient { get; private set; }
public static INetServer NetServer { get; private set; }
public static INetProvider NetProvider=>NetClient.IsConnected?NetClient as INetProvider:NetServer as INetProvider;
public static INetProvider NetProvider => (NetClient, NetServer) switch
{
(not null,null)=>NetClient as INetProvider,
(null,not null)=>NetServer as INetProvider,
(not null, { IsRunningServer: true }) =>NetServer as INetProvider,
({ IsConnected: true },not null) =>NetClient as INetProvider,
_ => null
};
[SerializeField] private MonoBehaviour netClient;
[SerializeField] private MonoBehaviour netServer;