Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 804
frc Avatar asked Jan 25 '17 14:01

frc


People also ask

How do I disconnect SignalR client?

SignalR version 2 does not have a built-in server API for disconnecting clients. There are plans for adding this functionality in the future. In the current SignalR release, the simplest way to disconnect a client from the server is to implement a disconnect method on the client and call that method from the server.

How do I set SignalR connection timeout?

Configuration. ConnectionTimeout = TimeSpan. FromSeconds(40); // Wait a maximum of 30 seconds after a transport connection is lost // before raising the Disconnected event to terminate the SignalR connection.

What is hubName in SignalR?

SignalR Hubs are a way to logically group connections as documented. Take an example of a chat application. A group of users could be part of the same hub which allows for sending messages between users in the group. The hubName here can be any string which is used to scope messages being sent between clients.


1 Answers

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.

like image 78
Jaroslav Kadlec Avatar answered Sep 26 '22 10:09

Jaroslav Kadlec