我的 SignalR 客户端有以下代码。根据我到目前为止的知识,这段代码应该打印“noitfyQueuePosition”事件发送的任何内容。
using Microsoft.AspNetCore.SignalR.Client;
Console.WriteLine("Connecting to Hub...");
var hubConnection = new HubConnectionBuilder().WithUrl("https://localhost:7178/queueHub").Build();
hubConnection.Closed += async (error) =>
{
Console.WriteLine("Connection closed. Reconnecting...");
await Task.Delay(new Random().Next(0, 5) * 1000);
await hubConnection.StartAsync();
};
hubConnection.On<string>("notifyQueuePosition", (queueCount) =>
{
Console.WriteLine($"Message received from server: {queueCount}");
});
try
{
await hubConnection.StartAsync();
Console.WriteLine("Connected to SignalR Hub.");
await hubConnection.InvokeAsync("JoinQueue", "fj294ij29r8jv09258jwr0fj2508f2trvjh2");
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to SignalR Hub: {ex.Message}");
}
Console.ReadLine();
我在另一个类中使用集线器的实例,并使用以下方法将队列计数发送到服务器中的每个连接。 “等待_queueHub.Clients.All.SendAsync(“notifyQueuePosition”,queueCount);“
问题是队列计数没有打印在我的客户控制台上。
我创建了一个后台服务并重现了您的问题,我收到如下错误。错误可能与您这边相同,如果不是,请检查下面的建议,它可以帮助您打印更多详细信息,例如我的图片。
然后我添加
Newtonsoft.Json
包并格式化数据,然后解决问题。
像下面这样
public Task AddToQueue(string userToken)
{
_queueManager.JoinQueue(userToken, Context.ConnectionId);
// using JsonConvert.SerializeObject to format the data
Clients.All.SendAsync("notifyQueuePosition", JsonConvert.SerializeObject(1));
return Task.CompletedTask;
}
// the method inside my test service
private void OnNotifyQueuePositionHandler(string queueCount)
{
var data = JsonConvert.DeserializeObject(queueCount);
Console.WriteLine($"Message received from server: {queueCount}");
}
这是我的完整代码。
using WebApplication2.IServices;
using Microsoft.AspNetCore.SignalR.Client;
using Newtonsoft.Json;
namespace WebApplication2.BackgroundServices
{
public class HubClientService : BackgroundService
{
private readonly IQueueManager _queueManager;
public HubClientService(IQueueManager queueManager)
{
_queueManager = queueManager;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
//Console.WriteLine(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + $" The number of members in the queue: {_queueManager?.UserQueue?.Count}");
//await Task.Delay(5000, stoppingToken);
Console.WriteLine("Connecting to Hub...");
var hubConnection = new HubConnectionBuilder().WithUrl("https://localhost:7245/queueHub").ConfigureLogging(logging =>
{
// Log to the Console
logging.AddConsole();
// This will set ALL logging to Debug level
logging.SetMinimumLevel(LogLevel.Debug);
}).Build();
hubConnection.Closed += async (error) =>
{
Console.WriteLine("Connection closed. Reconnecting...");
await Task.Delay(new Random().Next(0, 5) * 1000);
await hubConnection.StartAsync();
};
//hubConnection.On<string>("notifyQueuePosition", (queueCount) =>
//{
// Console.WriteLine($"Message received from server: {queueCount}");
//});
hubConnection.On<string>("notifyQueuePosition", OnNotifyQueuePositionHandler);
try
{
await hubConnection.StartAsync();
Console.WriteLine("Connected to SignalR Hub.");
await hubConnection.InvokeAsync("AddToQueue", "fj294ij29r8jv09258jwr0fj2508f2trvjh2");
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to SignalR Hub: {ex.Message}");
}
await Task.Delay(5000, stoppingToken);
}
}
public Func<string, Task>? NotifyQueuePositionHandler { get; set; }
private void OnNotifyQueuePositionHandler(string queueCount)
{
var data = JsonConvert.DeserializeObject(queueCount);
Console.WriteLine($"Message received from server: {queueCount}");
}
}
}
建议
我们需要启用信号器客户端日志记录以检查详细消息。
var connection = new HubConnectionBuilder()
.WithUrl("https://example.com/my/hub/url")
.ConfigureLogging(logging =>
{
// Log to the Console
logging.AddConsole();
// This will set ALL logging to Debug level
logging.SetMinimumLevel(LogLevel.Debug);
})
.Build();