【发布时间】: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 有什么解决办法吗?