How can a SignalR JavaScript client detect when a connection with the server is lost?
-
1Do you use signalr with asp.net? – Sinan AKYAZICI Feb 02 '12 at 10:45
7 Answers
A hub has a method disconnect
which will allow you to add a callback when disconnection takes place:
myHub.disconnect(function() {
alert('Server has disconnected');
});
If you aren't using hubs then the code for the disconnect method will help you out:
$(connection).bind("onDisconnect", function (e, data) {
callback.call(connection);
});
This shows the syntax for hooking onto the onDisconnect event of the underlying connection.

- 43
- 6

- 3,485
- 21
- 13
-
3
-
1The proper method for this is now `$.connection.hub.disconnected(callback)` – Jeremy Boyd Dec 07 '17 at 18:33
If you are using hubs then implement the IDisconnect interface.
public class ChatHub : Hub, IDisconnect
{
public void Disconnect()
{
Debug.WriteLine(Context.ConnectionId + " disconnected");
}
}
On persistent connections you can override OnDisconnectAsync, (from the SignalR wiki at https://github.com/SignalR/SignalR/wiki/PersistentConnection )
public class MyEndPoint : PersistentConnection
{
protected override Task OnDisconnectAsync(string clientId)
{
return Connection.Broadcast("Client " + clientId + " disconncted");
}
}

- 2,707
- 1
- 20
- 29
-
This is actually very useful as an answer unrelated to the question, thank you! – Josh Jul 24 '14 at 01:56
The SignalR 2.0 way of doing this is like so:
$.connection.hub.disconnected(function () {
console.log('Connection disconnected')
});

- 101
- 1
- 7
This worked for me using "@aspnet/signalr": "^1.0.0"
npm package
const connection = new signalr.HubConnectionBuilder()
.withUrl('url')
.configureLogging(signalr.LogLevel.Information)
.build()
connection.onclose(() => {
// close logic goes here
})

- 973
- 7
- 20
Starting with SignalR v0.5.1 it works this way:
$.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!");
}
});
For more details check this website:
http://weblogs.asp.net/davidfowler/archive/2012/06/10/signalr-0-5-1-released.aspx

- 418
- 4
- 11
The below, worked for me:
var connection = $.hubConnection('signalrConnectionUrl');
connection.disconnected(function() {
console.log('Connection disconnected');
});
I'm using version: 2.1.2
See the following link for reference: Link

- 443
- 8
- 12
The provided answers will no longer work. This is the new way to stop/disconnect connections.
myHub.stop().then(() => {
alert('Server has disconnected');
});

- 2,319
- 2
- 23
- 35