SignalR JavaScript 客户端如何检测与服务器的连接何时丢失?
问问题
32426 次
6 回答
32
集线器有一个方法disconnect
,允许您在断开连接时添加回调:
myHub.disconnect(function() {
alert('Server has disconnected');
});
如果您不使用集线器,则断开方法的代码将为您提供帮助:
$(connection).bind("onDisconnect", function (e, data) {
callback.call(connection);
});
这显示了挂钩到底层连接的 onDisconnect 事件的语法。
于 2012-02-03T00:48:06.100 回答
13
如果您使用集线器,则实现 IDisconnect 接口。
public class ChatHub : Hub, IDisconnect
{
public void Disconnect()
{
Debug.WriteLine(Context.ConnectionId + " disconnected");
}
}
在持久连接上,您可以覆盖 OnDisconnectAsync,(来自https://github.com/SignalR/SignalR/wiki/PersistentConnection的 SignalR wiki )
public class MyEndPoint : PersistentConnection
{
protected override Task OnDisconnectAsync(string clientId)
{
return Connection.Broadcast("Client " + clientId + " disconncted");
}
}
于 2012-02-02T23:02:11.640 回答
8
这对我使用"@aspnet/signalr": "^1.0.0"
npm 包有用
const connection = new signalr.HubConnectionBuilder()
.withUrl('url')
.configureLogging(signalr.LogLevel.Information)
.build()
connection.onclose(() => {
// close logic goes here
})
于 2018-10-03T07:15:17.663 回答
7
SignalR 2.0 的做法是这样的:
$.connection.hub.disconnected(function () {
console.log('Connection disconnected')
});
于 2014-07-30T16:14:10.447 回答
6
从 SignalR v0.5.1 开始,它以这种方式工作:
$.connection.hub.stateChanged(function (change) {
if (change.newState === $.signalR.connectionState.reconnecting) {
console.log("liveFeed is reconnecting!");
}
else if (change.newState === $.signalR.connectionState.connected) {
console.log("liveFeed is connected!");
}
});
有关更多详细信息,请查看此网站:
http://weblogs.asp.net/davidfowler/archive/2012/06/10/signalr-0-5-1-released.aspx
于 2012-10-20T11:14:53.387 回答
3
下面,为我工作:
var connection = $.hubConnection('signalrConnectionUrl');
connection.disconnected(function() {
console.log('Connection disconnected');
});
我正在使用版本:2.1.2
请参阅以下链接以供参考:链接
于 2015-01-30T09:58:40.157 回答