How can a SignalR JavaScript client detect when a connection with the server is lost?
If a server does not become available within the disconnect timeout period, the SignalR connection ends. In this scenario, the Closed event ( disconnected in JavaScript clients) is raised on the client but OnDisconnected is never called on the server.
To test reconnect after the server goes down use iisreset. To simulate client connection dropping (good luck) pull the network cable :) Pulling the network cable won't accurately simulate a client connection dropping when you're using Azure SignalR Service.
hub. stop(). done(function() { alert('stopped'); });
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.
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
})
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");
}
}
The SignalR 2.0 way of doing this is like so:
$.connection.hub.disconnected(function () {
console.log('Connection disconnected')
});
http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#connectionlifetime
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With