views:

380

answers:

3

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

+10  A: 

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.

Joel Spolsky
Thanks Joel, your suggestion makes a lot of sense. Would you happen to have a suggestion for a good starting-place to implement that On-Server poll to check/set users Offline - I've never really done something like that, despite how simple it sounds.
Jeff Dalley
probably worth another question... "how to run periodic processes on asp.net server" ...
Joel Spolsky
Thanks! I'll write that one up soon then - Appreciate it.
Jeff Dalley
+1  A: 

Javascript cannot be reliable, because I can close my browser by abending it.

A more reliable method might be to send periodic "hi I'm still alive" messages from the browser to the server, and have the server change the status when it stops receiving these messages.

ChrisW
+1  A: 

I can only agree with Joel here. There is no reliable way for you to know when the HTTP agent wants to terminate the conversation.

Franci Penov