Elkayam Gabay Elkayam Gabay - 5 days ago 5
jQuery Question

SignalR call OnDisconnect only after user closing the page/tab

So I'm using signalR to have online users list.
I used

stopCalled
to avoid that page refresh will be like disconnection, but now the user is never disconnecting..

public override Task OnDisconnected(bool stopCalled)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindByName(Context.User.Identity.Name);
string name = currentUser.NickName;
if (!(stopCalled))
{
var item = users.SingleOrDefault(x => x.Nick == name);
if (item != null)
users.Remove(item);
userNames.Remove(name);
Clients.All.hubReceived(users);
}
return base.OnDisconnected(stopCalled);
}


The user should only disconnect only when clicking on button (log off button)
or when his closing the tab/page.
What can i do?

Answer

stopCalled indicates whether the client disconnected gracefully or not, so your current method will remove only those users where the connections is gone (ex: network drop).

For a list of all online users, count the number of connections for each user.

OnConnected

  • if the user is not found in the list, add the user with count = 1
  • if the user is in the list, increment the count

OnDisconnected

  • decrease the count for that user
  • if for that user count = 0, remove the user from the list
Comments