【问题标题】:How to determine server disconnection from SignalR client?如何确定与 SignalR 客户端的服务器断开连接?
【发布时间】:2012-02-24 10:36:18
【问题描述】:

SignalR JavaScript 客户端如何检测与服务器的连接何时丢失?

【问题讨论】:

  • 你在 asp.net 中使用 signalr 吗?

标签: javascript long-polling signalr


【解决方案1】:

集线器有一个方法disconnect,它允许您在断开连接时添加回调:

myHub.disconnect(function() {
  alert('Server has disconnected');
});

如果您不使用集线器,则断开连接方法的代码将为您提供帮助:

$(connection).bind("onDisconnect", function (e, data) {
  callback.call(connection);
});

这显示了挂钩到底层连接的 onDisconnect 事件的语法。

【讨论】:

  • 不要使用 bind... 只是做 connection.disconnected
  • 现在正确的方法是$.connection.hub.disconnected(callback)
【解决方案2】:

如果您使用的是集线器,则实现 IDisconnect 接口。

public class ChatHub : Hub, IDisconnect
{
    public void Disconnect()
    {
        Debug.WriteLine(Context.ConnectionId + " disconnected");
    }
}

在持久连接上,您可以覆盖 OnDisconnectAsync, (来自 SignalR wiki https://github.com/SignalR/SignalR/wiki/PersistentConnection

public class MyEndPoint : PersistentConnection 
{
    protected override Task OnDisconnectAsync(string clientId) 
    {
        return Connection.Broadcast("Client " + clientId + " disconncted");   
    }
}

【讨论】:

  • 这作为与问题无关的答案实际上非常有用,谢谢!
【解决方案3】:

这对我有用 "@aspnet/signalr": "^1.0.0" npm 包

const connection = new signalr.HubConnectionBuilder()
    .withUrl('url')
    .configureLogging(signalr.LogLevel.Information)
    .build()

connection.onclose(() => {
   // close logic goes here
})

【讨论】:

    【解决方案4】:

    SignalR 2.0 的做法是这样的:

    $.connection.hub.disconnected(function () {
        console.log('Connection disconnected')
    });
    

    http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#connectionlifetime

    【讨论】:

      【解决方案5】:

      从 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

      【讨论】:

        【解决方案6】:

        以下对我有用:

        var connection = $.hubConnection('signalrConnectionUrl');
        
        connection.disconnected(function() {
            console.log('Connection disconnected');
        });
        

        我正在使用版本:2.1.2

        参考以下链接:Link

        【讨论】:

          猜你喜欢
          • 2015-05-17
          • 2021-12-05
          • 2012-04-05
          • 1970-01-01
          • 1970-01-01
          • 2013-03-31
          • 1970-01-01
          • 2014-05-26
          • 1970-01-01
          相关资源
          最近更新 更多