使用Socket.io实现特定用户离线通知功能技术求助
Implementing Offline Notifications with Socket.io
Got it, let's build that offline notification logic to match your existing online setup! The core idea is to mirror how you handle online alerts—we'll listen for an offline event, locate the relevant users, and send a targeted notification to the specific user who needs to know.
Here's the code, aligned with your current pattern:
// Listen for the Offline event (same parameter structure as your Online event: recipient ID, user who went offline) socket.on("Offline", function(UserOneID, UserTwoID) { // Find the user who should receive the notification (UserOne) var UserOne = UserOnline.find(f => f.UserId == UserOneID); // Find the user who just went offline (UserTwo) var UserTwo = UserOnline.find(f => f.UserId == UserTwoID); // Only send the notification if the recipient is online AND the offline user was tracked if (!isNullOrUndefined(UserOne) && !isNullOrUndefined(UserTwo)) { // Send the offline alert to the recipient's socket io.to(UserOne.socketId).emit("OfflineAlert", "User " + UserTwo.UserId + " is offline now"); } });
Quick Notes to Keep in Mind:
- Socket ID Check: I noticed your original online code uses
io.to(UserOne)—that's probably a typo! You need to pass the actual socket ID of the user (likeUserOne.socketId) sinceio.to()targets a specific socket connection. Make sure yourUserOnlineobjects store thesocketIdproperty for each user. - Timing is Key: Trigger this
Offlineevent before removing the user from theUserOnlinearray. If you remove them first,UserTwowill come up as undefined and the notification won't send. - Customize Event Names: Feel free to rename
OfflineAlertto whatever event name your client is set up to listen for (e.g., "UserWentOffline").
内容的提问来源于stack exchange,提问作者Samarth Mehta
相关产品推荐
相关产品推荐

