68 lines
1.9 KiB
C#
68 lines
1.9 KiB
C#
|
using System;
|
||
|
using Microsoft.AspNetCore.SignalR.Client;
|
||
|
using UnityEngine;
|
||
|
using System.Threading.Tasks;
|
||
|
using BITKit;
|
||
|
using Cysharp.Threading.Tasks;
|
||
|
using Microsoft.Extensions.Logging;
|
||
|
|
||
|
public class SignalRClient : MonoBehaviour
|
||
|
{
|
||
|
[SerializeField] private string url = @"https://yourserver.com/chathub";
|
||
|
|
||
|
private HubConnection _connection;
|
||
|
|
||
|
private ILogger<SignalRClient> _logger;
|
||
|
|
||
|
private StopWatcher _stopWatcher;
|
||
|
// 用于与 SignalR 服务器进行通信
|
||
|
private async void Start()
|
||
|
{
|
||
|
await UniTask.Delay(300);
|
||
|
|
||
|
if(destroyCancellationToken.IsCancellationRequested)return;
|
||
|
|
||
|
_connection = new HubConnectionBuilder()
|
||
|
.WithUrl(url)
|
||
|
.Build();
|
||
|
|
||
|
BITApp.ServiceProvider.QueryComponents(out _logger);
|
||
|
|
||
|
_connection.On<string, string>("ReceiveMessage", (user, message) =>
|
||
|
{
|
||
|
_stopWatcher?.Dispose();
|
||
|
_logger.LogInformation($"Received from Blazor/Server: {user} - {message}");
|
||
|
});
|
||
|
|
||
|
destroyCancellationToken.Register(Dispose);
|
||
|
|
||
|
await _connection.StartAsync();
|
||
|
_logger.LogInformation("Unity connected to SignalR server!");
|
||
|
|
||
|
// 发送消息给 Blazor
|
||
|
await SendMessageToBlazor("Unity", "Hello from Unity!");
|
||
|
|
||
|
for (var i = 0; i < 16; i++)
|
||
|
{
|
||
|
_stopWatcher = new StopWatcher(_logger, $"SignalR延迟 at {i}");
|
||
|
|
||
|
await SendMessageToBlazor("Unity", "OK,Let's Count!");
|
||
|
}
|
||
|
|
||
|
var id = await _connection.InvokeAsync<string>("GetMessage");
|
||
|
|
||
|
_logger.LogInformation($"获取用户ID:{id}");
|
||
|
|
||
|
}
|
||
|
|
||
|
private async void Dispose()
|
||
|
{
|
||
|
await _connection.StopAsync();
|
||
|
}
|
||
|
|
||
|
private async Task SendMessageToBlazor(string user, string message)
|
||
|
{
|
||
|
await _connection.InvokeAsync("SendMessage", user, message);
|
||
|
}
|
||
|
|
||
|
}
|