Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running server-side function as browser closes

Background: I'm creating a very simple chatroom-like ASP.NET page with C# Code-Behind. The current users/chat messages are displayed in Controls located within an AJAX Update Panel, and using a Timer - they pull information from a DB every few seconds.

I'm trying to find a simple way to handle setting a User's status to "Offline" when they exit their browser as opposed to hitting the "Logoff" button. The "Offline" status is currently just a 1 char (y/n) for IsOnline.

So far I have looked into window.onbeforeunload with Javascript, setting a hidden form variable with a function on this event -> Of course the trouble is, I'd still have to test this hidden form variable in my Code-Behind somewhere to do the final Server-Side DB Query, effectively setting the User offline.

I may be completely obfusticating this likely simple problem! and of course I'd appreciate any completely different alternative suggestions.

Thanks

like image 530
Jeff Dalley Avatar asked Feb 10 '09 03:02

Jeff Dalley


1 Answers

I suspect you are barking up the wrong tree. Remember, it is possible for the user to suddenly lose their internet connection, their browser could crash, or switch off their computer using the big red switch. There will be cases where the server simply never hears from the browser again.

The best way to do this is with a "dead man's switch." Since you said that they are pulling information from the database every few seconds, use that opportunity to store (in the database) a timestamp for the last time you heard from a given client.

Every minute or so, on the server, do a query to find clients that have not polled for a couple of minutes, and set the user offline... all on the server.

like image 119
Joel Spolsky Avatar answered Sep 22 '22 12:09

Joel Spolsky