SignalR 如何避免连接两次
SignalR how to avoid connecting twice
在我的应用程序中,一旦我登录,我就会重定向到主页,其中有以下脚本:
// Defining a connection to the server hub.
var myHub = $.connection.myHub;
// Setting logging to true so that we can see whats happening in the browser console log. [OPTIONAL]
$.connection.hub.logging = true;
// Start the hub
$.connection.hub.start();
myHub.client.newMessageReceived = function (message) {
alert(message);
}
在我的 Hub.cs 服务器中我有:
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
// here do other stuff...
return base.OnConnected();
}
第一次进入主页时,我看到了 connectionId
,但是如果我再次重新加载页面,我会看到一个不同的页面,这是因为 jquery 脚本再次被召唤。
How can I detect in my client if Im already connected so I dont start()
the hub everytime I refresh that page?
我有一个类似的场景,其中重定向启动了另一个连接到 SignalR 的请求 - 我通过检查 connection.state
并过滤掉请求来解决,除非连接处于 Disconnected
状态。我使用的是 angular + rxjs,但希望类似的原则仍然适用:
在中心服务中
this.connection = new HubConnectionBuilder()
.withUrl(`${environment.apiUrl}/hubRoute`)
.configureLogging(LogLevel.Warning)
.build();
然后在请求中连接到SignalR
filter(() => this.hubService.connection.state === HubConnectionState.Disconnected)
// safe to call hubService.connection.start();
希望能帮助遇到同样问题的其他人!
在我的应用程序中,一旦我登录,我就会重定向到主页,其中有以下脚本:
// Defining a connection to the server hub.
var myHub = $.connection.myHub;
// Setting logging to true so that we can see whats happening in the browser console log. [OPTIONAL]
$.connection.hub.logging = true;
// Start the hub
$.connection.hub.start();
myHub.client.newMessageReceived = function (message) {
alert(message);
}
在我的 Hub.cs 服务器中我有:
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
// here do other stuff...
return base.OnConnected();
}
第一次进入主页时,我看到了 connectionId
,但是如果我再次重新加载页面,我会看到一个不同的页面,这是因为 jquery 脚本再次被召唤。
How can I detect in my client if Im already connected so I dont
start()
the hub everytime I refresh that page?
我有一个类似的场景,其中重定向启动了另一个连接到 SignalR 的请求 - 我通过检查 connection.state
并过滤掉请求来解决,除非连接处于 Disconnected
状态。我使用的是 angular + rxjs,但希望类似的原则仍然适用:
在中心服务中
this.connection = new HubConnectionBuilder()
.withUrl(`${environment.apiUrl}/hubRoute`)
.configureLogging(LogLevel.Warning)
.build();
然后在请求中连接到SignalR
filter(() => this.hubService.connection.state === HubConnectionState.Disconnected)
// safe to call hubService.connection.start();
希望能帮助遇到同样问题的其他人!