【问题标题】:Signalr client doesn't get hub messages?Signalr 客户端没有收到集线器消息?
【发布时间】:2021-12-22 23:18:18
【问题描述】:

我正在使用 .net core 5 进行简单设置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<ChatHub>("/chathub");
        endpoints.MapControllers();
    });
}

有了这个简单的集线器:

public interface IChatClient
{
    Task SendMessage( string message);
}

public class ChatHub : Hub<IChatClient>
{
    public Task SendMessage(string message)
    {
        return Clients.All.SendMessage(   message);
    }
}

这是我的简单控制器:

public class WeatherForecastController : ControllerBase
{
    private readonly IHubContext<ChatHub> _hubContext;

    

    public WeatherForecastController(IHubContext<ChatHub> hubContext)
    {
        _hubContext = hubContext;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        await _hubContext.Clients.All.SendAsync("ReceiveMessage", $"Home page loaded at: {DateTime.Now}");
        return Ok();
    }
}

(为简单起见,只要调用 GET HTTP 端点,就应该发送一条消息)。

C# 控制台客户端是:

async Task Main()
{
    var uri = "http://localhost:5000/chatHub";
    await using var connection = new HubConnectionBuilder().WithUrl(uri).Build();

    await connection.StartAsync();
    connection.On<string>("ReceiveMessage", (message) => Console.WriteLine(message));

    
}

问题:

这两个应用程序都在运行,但是当我刷新页面时,我在客户端没有看到任何消息。 我可能在这里遗漏了一些东西。

【问题讨论】:

    标签: c# signalr asp.net-core-webapi


    【解决方案1】:

    您的客户端(控制台)应用程序很可能在任何消息到达之前就存在。你有:

    await using var connection
    

    这将处理连接和范围的结束,也就是方法的结束。 connection.On 不是阻塞调用,它只是订阅消息。所以最后你的连接会立即被释放,你的应用程序就会退出。

    只需在末尾添加Console.ReadKey() 之类的内容即可进行测试。或者,不要在作用域的末尾释放连接。

    更新:您说您正在使用 LINQPad 和 Util.keeprunning() 方法。这在这种情况下无济于事,因为keeprunning() 不是阻塞调用,它会阻止进程退出,是的,直到您处理此方法返回的内容,但控制仍然离开您的方法,这意味着由于以下原因而处理了连接async using var connection = ...。您需要删除它并在某些情况下明确处理连接(例如收到 2 条消息)。

    【讨论】:

    • 我没有写它,因为我认为它无关紧要,但我在 linqpad 中运行它并使用:util.keeprunning()。所以我不认为这是问题所在。我在办公室 10 分钟后再次检查
    • @RoyiNamir Util.keeprunning 将无济于事,因为虽然进程可能不会退出 - 由于 await using ... 仍会释放连接(keeprunning 也不是阻塞调用)。在这种情况下,不要释放连接。
    • 例如,只有在收到say 2条消息后,连同keeprunning的结果一起处理。
    猜你喜欢
    • 2021-10-18
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多