You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 (like UserOne.socketId) since io.to() targets a specific socket connection. Make sure your UserOnline objects store the socketId property for each user.
  • Timing is Key: Trigger this Offline event before removing the user from the UserOnline array. If you remove them first, UserTwo will come up as undefined and the notification won't send.
  • Customize Event Names: Feel free to rename OfflineAlert to whatever event name your client is set up to listen for (e.g., "UserWentOffline").

内容的提问来源于stack exchange,提问作者Samarth Mehta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:11:57