使用IHubContext从托管服务检查有效的SignalR连接

问题描述

我有一个托管服务,该服务通过SignalR向客户端发送消息,并且客户端正在拾取消息并在剃刀页面显示。这是精简版。

这很好用,只是在实例化托管服务后调用.js文件,这意味着未及时为第一条消息建立连接,因此这些消息将丢失。

在发送任何内容之前,是否可以使用IHubContext检查连接?还是我需要对整个方法进行更根本的改变?

JavaScript(链接到“索引”页面

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/logHub").build();
connection.start()

connection.on("ReceiveLogNotification",function (msg) {
    console.log("JS: " + msg);
});

集会班

public class LogHub : Hub
{
}

托管服务

public class MsgGenerator : IHostedService
{
    private Random _random;
    private Microsoft.Extensions.Logging.ILogger _logger;
    private Timer? _timer;
    private readonly IHubContext<LogHub> _hubContext;

    public LogGenerator(ILogger<LogGenerator> logger,IHubContext<LogHub> hubContext)
    {
        _logger = logger;
        _random = new Random();
        _timer = null;
        _hubContext = hubContext;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        ScheduleNextMessage();
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    private void ScheduleNextMessage()
    {
        var nextTime = TimeSpan.FromMilliseconds(_random.Next(1000));
        _timer = new Timer((state) => { GenerateMessage(); },null,nextTime,TimeSpan.Zero);
    }

    private async void GenerateMessage()
    {
        await _hubContext.Clients.All.SendAsync("ReceiveLogNotification","test message");
        ScheduleNextMessage();
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)