如何通过Quickblox判断用户在线状态?基于JavaScript SDK视频聊天场景
Great question! The last_requested_at field is indeed limited since it only updates on initial login, so it won't reflect real-time presence changes like sudden disconnections. Here are the most reliable methods to get accurate online status for your video chat app:
1. Use QuickBlox's Native Presence Module (Recommended)
QuickBlox has a built-in Presence system designed specifically for real-time user status tracking. It supports push notifications for status changes, so you'll get instant updates when a user comes online or goes offline.
Key Implementation Steps:
- Subscribe to user presence: First, subscribe to the users you want to monitor. This lets you receive status updates for them.
// Subscribe to a single user's presence QB.presence.subscribe(USER_ID, function(error, response) { if (error) { console.error("Failed to subscribe:", error); } else { console.log("Subscribed to user presence:", response); } }); // Subscribe to multiple users QB.presence.subscribeMultiple([USER_ID_1, USER_ID_2], function(error, response) { // Handle result }); - Listen for presence updates: Set up event listeners to catch when a user's status changes:
// Listen for online status updates QB.events.onPresenceUpdateListener = function(presence) { console.log("User", presence.userId, "is now", presence.type); // "online" or "offline" // Update your UI or app state here }; // Listen for subscription requests (if you need to approve/reject access) QB.events.onSubscriptionListener = function(request) { QB.presence.respondSubscription(request.userId, true, function(error) { if (!error) console.log("Subscription approved for user:", request.userId); }); }; - Check current status on demand: If you need to fetch a user's status immediately:
QB.presence.status([USER_ID], function(error, response) { if (!error) { const userStatus = response[0]; console.log("User", userStatus.userId, "current status:", userStatus.type); } });
2. Combine with Chat Socket Connection Status
Since your video chat relies on QuickBlox's chat WebSocket, you can use socket connection events as an extra layer to verify presence:
// Listen for unexpected disconnections QB.chat.onDisconnectedListener = function() { console.log("Current user lost chat connection"); // Mark the current user as offline in your app state }; // Listen for reconnections QB.chat.onReconnectedListener = function() { console.log("Current user reconnected to chat"); // Mark the current user as online again };
This helps catch cases where a user loses internet abruptly, which the Presence module should handle, but it's a solid fallback for edge cases.
3. Custom Heartbeat Mechanism (Fallback)
If you need more control (like tracking "idle" status), implement a custom heartbeat system:
- Set a timer to send a request updating a custom user field (e.g.,
last_active_at) every few minutes. - When checking a user's status, compare their
last_active_attimestamp to the current time. If it's within your threshold (e.g., 5 minutes), consider them online.
Example code for sending heartbeats:
function sendHeartbeat() { const currentTimestamp = Math.floor(Date.now() / 1000); QB.users.update({id: QB.session.userId, last_active_at: currentTimestamp}, function(error, user) { if (!error) console.log("Heartbeat sent successfully"); }); } // Send heartbeat every 2 minutes setInterval(sendHeartbeat, 120000);
Final Notes
The Presence module is the most reliable and efficient method because it's built into QuickBlox and handles real-time updates out of the box. Use socket events and custom heartbeats as supplementary checks only if you need extra validation for specific edge cases.
内容的提问来源于stack exchange,提问作者user33333

