Using SignalR Hubs, connection is lost after some

2019-06-24 05:53发布

问题:

In my SignalR app, callbacks are fired as expected on a page. If the page is left for some time, callbacks are no longer invoked on that page until it is refreshed.

I suspect that this could be due to the site's session expiring (using a client's session ID to invoke a client notification).

I read here about the KeepAlive functionality and can see some references to it in the SignalR code. I am unclear if a client-side keep-alive needs to be implemented, and if so, how?

回答1:

I haven't made any experiments or checked the documentation but your assumption makes sense. SignalR does not support session for various good reasons. If it does not support reading from the session then it is reasonable to expect that it will not refresh the Session expiration time. However if you really need to use Session ID as the client ID (which you should not) then implementing a kind of keep alive is easy. Just write some JS to call the server (a Session enabled HTTP handler for example) in the simplest manner without doing any work. It will serve only to refresh the Session expiration time.



回答2:

Have a look http://www.asp.net/signalr/overview/signalr-20/hubs-api/handling-connection-lifetime-events

  $.connection.hub.disconnected(function() {
      alert('disconnected')
      setTimeout(function() {
        alert('reconnecting')
        $.connection.hub.start();
      }, 5000); // Restart connection after 5 seconds.
    });