Search code examples
c#asp.net-mvcwebsocketsignalr

Detect on disconnect user signalr


I need to detect when users connect and disconnect using signalr.

I have these 2 hub methods:

public void Say(string message)
{
    Trace.WriteLine(message + " - " + Context.ConnectionId);
}

public void Goodbye(string message)
{
    Trace.WriteLine(message + " - " + Context.ConnectionId);
}

I have implemented the Say method which takes care of detecting a connection like so:

$.connection.hub
            .start()
            .done(function () {
                hub.server.say("Hello SignalR");
});

But how do I detect disconnect?


Solution

  • Add this overriden method into your Hub class:

    public override Task OnDisconnected(bool stopCalled)
    {
        // do the logging here
        Trace.WriteLine(Context.ConnectionId + ' - disconnected');
        return base.OnDisconnected(stopCalled);
    }
    

    This will handle and log disconects on server side while I think it doesn't make much sense to track it on client side as it's unlikely your SignalR session would be terminated from server side - see here.

    Edit in regard to @stuartd comment: you could also override

    public override Task OnReconnected()
    {
        Trace.WriteLine(Context.ConnectionId + ' - reconnected');
        return base.OnReconnected();
    }
    

    so you'll be able to track cases when Client tried reconnect to Server and succeed.

    Edit#2: Then you can of course use same mechanism for tracking of OnConnected event

    public override Task OnConnected()
    {
        Trace.WriteLine(Context.ConnectionId + ' - reconnected');
        return base.OnConnected();
    }
    

    So all tracking code is conveniently kept just on server-side which is more robust in cases when client is logged into hub but for some reason failed to execute method you're using to track logged state.