【问题标题】:SignalR cannot send a message to all connected clientsSignalR 无法向所有连接的客户端发送消息
【发布时间】:2018-04-18 01:23:36
【问题描述】:

我正在尝试使用 SignalR 向所有连接的客户端发送消息。

我找到了几个示例,并添加了我认为是所有必需的部分。我确实成功地让我的客户连接到我的集线器。我无法让我的服务器连接到我的 Hub 并向所有连接的客户端发送消息。

当我调用 DatabaseChangeListener::Notify() 时,它永远不会命中 Hub 中的代码。

谁能建议我还需要做什么?

我在带有 React 和 Redux 的 Web 应用程序中使用 .NET Core 2.1 preview 2。

我正在使用 SignalR 1.0.0-preview2-final

我正在使用 SignalR.Client 1.0.0-preview2-final

在 Startup.cs 中

    public void ConfigureServices(IServiceCollection services)
    {
      // remove all other code for this question
      services.AddSignalR();
    }

    public void Configure(IApplicationBuilder app)
    {
      // remove all other code for this question
      app.UseSignalR(routes =>
      {
        routes.MapHub<SignalRHub>("/hubs/update");
      });
    }

我的中心

    [Authorize]
    public class SignalRHub : Hub
    {
        public async Task Send(string message)
        {
            await Clients.All.SendAsync("SendMessage", Context.User.Identity.Name, message);
        }   
    }

我的班级通知客户

public class DatabaseChangeListener : IDatabaseChangeListener
{
    private readonly IHubContext<SignalRHub> _hubContext;

    public DatabaseChangeListener(IHubContext<SignalRHub> hubContext)
    {
            _hubContext = hubContext;

    }

    public void Notify()
    {
      _hubContext.Clients.All.SendAsync("SendMessage", "something changed, Yo");
    }
}

【问题讨论】:

  • 我假设您没有从客户端启动连接。你能出示这段代码吗?
  • 如果您只打算使用 IHubContext 发送消息,则可以安全地删除 SignalRHub 中的 Send 方法。仅当您收到来自客户端的消息时才会调用集线器中的方法,而不是发送给他们的消息。
  • @Zamboni 有什么解决办法吗?

标签: signalr asp.net-core-2.0


【解决方案1】:

您需要通过客户端建立与集线器的连接,然后使用您的 _hubContext,您应该能够根据与集线器的连接向客户端发送消息。

使用 JS 从客户端连接到集线器。

    const connection = new signalR.HubConnectionBuilder()
        .withURL("/YourHub")
        .build();

那么在建立连接之后,你也可以使用JS从服务器向客户端发送消息的方法。

    connection.on("SendMessage", message => {
        document.getElementById("IdOfElementToDisplayMessage").innerHTML = message;
    });

最后补充:

    connection.start().catch(err => console.error(err.toString()));

现在您已通过客户端建立到集线器的连接,现在可以从 IHubContext 引用到集线器的连接。 要从服务器向客户端发送消息,您可以使用_hubContext

在您的情况下,您可以调用Notify(),然后调用await _hubContext.Clients.All.SendAsync("SendMessage", "something changed, Yo");,这应该将您的消息发送到在JS中创建的SendMessage方法:connection.on("SendMessage", message =&gt; { ...

如果您的_hubContext 变量在执行期间为空,则需要检查 IHubContext 的注入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 2017-07-01
    • 2018-05-19
    相关资源
    最近更新 更多