SignalR HUb如何使用IHubContext c#



我需要一些帮助,以了解他们是否对signalR做了错误的事情。放手:

我的应用程序是mvc。我按照教程中的例子做了:

我创建了一个RealTime类:

public class RealTime : Hub
{
public async Task SendMessage(string message)
{
await Clients.All.SendAsync("ReceiveMessage", message);
}
}

启动中:

public void ConfigureServices(IServiceCollection services)
{
.
.
.
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
{
.
.
.
app.UseSignalR(routes =>
{
routes.MapHub<RealTime>("/realtime");
});
}

所以,我去了我的控制器并注入了IHubContext:

public class MyController : Controller
{
private readonly IHubContext<RealTime> _hub;
public MyController
(
IHubContext<RealTime> hub
)
{
_hub = hub;
}

在某个时刻,我使用:

await _hub.Clients.All.SendAsync("ReceiveMessage", "Hello Word!");

在我的前端,我做了以下操作:

var connection = new signalR.HubConnectionBuilder().withUrl("/realtime").build();
connection.on("ReceiveMessage", function (message) {
Swal.fire(
'The Internet?',
message,
'question'
);
});
connection.start().then(function () {
//
}).catch(function (err) {
//
});

但什么也没发生。无论是后端还是前端都没有错误。但什么也没发生!

有人能告诉我我做错了什么吗?

我注意到的第一件事是,您在一个控制器中注入了集线器,尝试将其注入在该控制器中调用的服务/管理器中。第二件事是,当您不在实现Hub的类中时,最好使用SendCoreAsync()而不是SendAsync。我可以建议你做的第三件事是放.configureLogging(signalR.LogLevel.Information) and then .build();此外,将此设置为不出现错误:import * as signalR from "@aspnet/signalr";同时启动连接并显示消息以了解连接是否已建立

connection.start().then(function () {
console.log("signalR connected")
}).catch(function (err) {
console.log(err)
});

只有在启动连接后,我才会打开连接

connection.on("ReceiveMessage", (message) =>{
Swal.fire(
'The Internet?',
message,
'question'
);
});

希望我帮了你!

感谢您的帮助。我找到了解决方案,尽管效果很糟糕。

在打开连接之前,我放了以下片段:

Object.defineProperty(WebSocket, 'OPEN', { value: 1, });

所以我的js是这样的:

var connection = new signalR.HubConnectionBuilder()
.withUrl("/realtime")
.configureLogging(signalR.LogLevel.Debug)
.build();
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
connection.start().then(function () {
console.log("signalR connected")
}).catch(function (err) {
return console.error(err)
});
connection.on("ReceiveMessage", function (message) {
Swal.fire(
'The Internet?',
message,
'question'
);
});

相关内容

最新更新