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