[英]How to show online users with ajax
我想在我的網站上實時顯示所有在線用戶。 不知道如何解決這個問題。 登錄后添加新用戶並不困難,但我還需要刪除未登錄的用戶。
知道怎么做嗎? 我應該用jQuery檢查用戶已經刪除了什么並從列表中刪除它們等?
您的問題將是人們在沒有退出的情況下導航,他們的會話仍將存在,因為您的會話數據需要收集之前設置超時(實際上可能更長)
要准確計算誰登錄並訪問該站點,您需要每個客戶端每隔幾秒或幾分鍾向服務器發送一次“心跳”。 在每個心跳觸發器上,您希望使所有未在指定時間范圍內簽入的用戶到期。
心跳信號可能最好由用戶名和時間戳組成,但可能包含您要跟蹤的任何信息。
當客戶端向服務器發送單個數據庫時,它會檢查該用戶名的現有記錄,並在記錄已存在時覆蓋時間戳信息,否則添加新記錄。 Afterwords刪除任何未簽入的用戶條目。可能最好讓信號比到期時更頻繁地發生。 像信號每30秒一樣,每分鍾清理一次。
(編輯,改變了主意,最好以相同的順序而不是單獨執行)然后從活動表返回當前登錄的用戶,這將像SELECT * FROM table
一樣簡單,因為表將始終是干凈的。
下面是一個客戶端庫的示例,用於處理觸發心跳功能和捕獲結果。
//Client-side parent variable declaration (simulated namespacing)
var Client = Client || {};
Client.Pulse = null; //Holds a pointer to the heartbeat timer (id)
/* If you needed to cancel the heartbeat processes you could
* pass this variable to clearTimeout(). Calling Client.Heartbeat()
* again would start the cycle back up.
*/
//Initial event that will kick off the chain when the DOM is ready
$(document).ready(function(){
Client.Heartbeat(); //Initial call to the Heartbeat function
});//ready
/// Sends the heartbeat signal and retrieves the currently active user list
Client.Heartbeat = function(){
var sUsername = 'SomeUser';
/* Note: If you have an active session running on the server it would not be
* necessary to send the username since you could pull it on the backend
* script which would be more tamper-proof anyway. I'm just giving an
* example of sending data to the server using the jQuery.ajax method
* If you were storing the username to be sent from the client; this wouldn't
* be a good place to do it anyway
*
* Remove the "data : {...}" line below to exclude sending information to the server
* The "type : 'post'" line would not be necessary either
*/
$.ajax({ //Send the signal and recieve the information about active users back
url : '/lib/server/Heartbeat.php',
type : 'post',
dataType : 'json',
data : {Username : sUsername },
success : function(jActiveUsers,sStatus,jqXHR){
/* This is the callback function of the request, jActiveUsers will be the
* json object with the information you choose to send back to it
*/
Client.RenderActiveUsers(jActiveUsers); //Call the display function
//Trigger the next delayed call to Client.Heartbeat
Client.Pulse = setTimeout(function(){
Client.Heartbeat();
},30000); //30 second delay before next trigger
}//success
});//$.ajax
}//Heartbeat
/// Processes the results sent by the server and draws them to the UI
Client.RenderActiveUsers = function(jActiveUsers){
/* This is where you would get a handle whatever element(s) on the page
* will be displaying the information about currently active users
* and filling it with the list of users how ever you would wish to display it.
*/
}//RenderActiveUsers
因為你將處理異步回調setTimeout()
調用在一個完整周期結束時重新啟動進程將是一個更簡潔的處理間隔的方法,如果你使用setInterval()
並且服務器花了比預期更長的時間回來你可以看到客戶開始競爭自己。 在成功回調中使用setTimeout()
還可以在服務器端心跳處理器停止工作時正常失敗; 客戶端也是如此,而不是繼續嘗試失敗(如果你希望它繼續嘗試你只需要在失敗的響應上添加重新觸發)。
我很抱歉我不熟悉Java作為后端服務,我將根據PHP的工作原理做一些假設; 所以我無法保證它會直接映射到您的環境。 數據庫示例將假設MySQL。 代碼示例將是偽代碼PHP(ish)
在服務器端,您將需要一個新表來跟蹤活動用戶。 您可能已經在數據庫中登錄時進行跟蹤,但這將與該系統分開(盡管您可以鏈接到它以獲取返回結構的額外用戶詳細信息)
該表將至少看起來像:
ActiveUsers
-----------------------------------------
| Field | Type | NULL | Key |
-----------------------------------------
| Id | int | | PRI |
| Username | varchar(xx) | | |
| LastPulse | datetime | | |
| FirstPulse | datetime | | |
-----------------------------------------
(推測)我假設像PHP一樣,Java中有Sessions
,您可以使用它來存儲特定訪問者的信息,例如他們當前的狀態。 在PHP中,這通過在客戶端和服務器之間來回傳遞標識符來工作,允許服務器識別特定客戶端,並在后端存儲與該會話相關的變量(例如,具有當前登錄狀態的布爾值)用戶或登錄后用於保存用戶名的字符串。)
如果您可以使用它,那么處理身份驗證的方式要比在客戶端存儲此信息更安全,並允許客戶端指示是否以及登錄的人員。這里假設它是....
當客戶端將心跳發送到服務器時,如果它們事實上已登錄以開始該過程,則可以從會話變量訪問其登錄狀態和用戶名。
if($LoggedIn && ($Username != null)){ //Session information
如果他們沒有登錄,您將跳到列表檢索部分,因為您不需要為它們添加或修改記錄
檢查它們是否在活動表中有記錄
SELECT `Id` FROM `ActiveUsers` WHERE `Username` = '{$Username}' LIMIT 1
如果存在記錄,則表示它們之前已經簽入,並且您希望使用從第一個查詢返回的Id值使用新時間戳更新記錄
UPDATE `ActiveUsers` SET `LastPulse` = NOW() WHERE `Id` = {$Id}
如果不存在記錄,則需要為此用戶創建一個新記錄
INSERT INTO `ActiveUsers` (`Username`,`LastPulse`,`FirstPulse`) VALUES ('{$Username}',NOW(),NOW())
接下來是流程的維護階段,在此過程中,您要清除未設置的任何條目,並將其設置為您要設置為限制的時間(本示例中為2分鍾)
DELETE FROM `ActiveUsers` WHERE `LastPulse` < (NOW() - INTERVAL 2 MINUTE)
這將留下您的ActiveUsers
表,以便只存在您可以查詢以獲取的活動用戶的記錄,以及您希望從此處以及您可以鏈接到的任何其他表中獲得的任何其他信息
SELECT `Username`, UNIX_TIMESTAMP(`FirstPulse`) AS `FirstPulse` FROM `ActiveUsers` ORDER BY `FirstPulse` ASC
(在PHP中)然后,您需要循環結果集並構建一個用戶數組,通過調用json_encode()
和print()
以及"application/json"
標頭值將其轉換為JSON,以便jQuery可以正確處理它。 這當然會在實現中的Java之間有所不同,但是“創建一個數組,將其轉換為JSON字符串並使用指定的正確標頭打印出來”的整個過程將是相同的。
理想情況下,您希望將客戶端盡可能“愚蠢”地保留在任何類型的身份驗證過程中。 在此示例中,客戶端盲目地檢入服務器並僅通過詢問活動用戶的新列表來觸發過期用戶的清理。
如果100%准確的列表在高度利用的站點上是關鍵任務的,則可能需要在執行維護部分時鎖定表。 確保在另一個線程處於簽入階段時不會發生對用戶列表的查詢。
(哇,這變成了一個Wall-O-Text)
您可以定期對服務器進行ajax調用,並檢查當前登錄的數量。 您可以使用setInterval設置計時器以觸發ajax請求。 答復將包含否。 目前有效的用戶
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.