Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine server disconnection from SignalR client?

How can a SignalR JavaScript client detect when a connection with the server is lost?

like image 627
Alexandr Avatar asked Feb 01 '12 18:02

Alexandr


People also ask

What causes SignalR to disconnect?

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.

How do I check if my SignalR is reconnecting?

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.

How do I stop SignalR connection?

hub. stop(). done(function() { alert('stopped'); });


4 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.

like image 129
John Rayner Avatar answered Oct 02 '22 19:10

John Rayner


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
})
like image 33
Ross Jones Avatar answered Oct 02 '22 19:10

Ross Jones


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");   
    }
}
like image 38
MatteKarla Avatar answered Oct 02 '22 18:10

MatteKarla


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

like image 41
gholmes Avatar answered Oct 02 '22 19:10

gholmes