Running server-side function as browser closes

 ̄綄美尐妖づ 提交于 2019-12-22 04:47:15

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/531001/running-server-side-function-as-browser-closes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!