添加用户在线状态更新

This commit is contained in:
2026-09-24 10:31:27 +08:00
parent 74ed1535ed
commit 4c3b99edac
2 changed files with 46 additions and 15 deletions
+22 -9
View File
@@ -8,6 +8,8 @@ const {
addConnection,
getConnection,
removeConnection,
getOnlineUsers,
broadcast
} = require("./connectionManager");
// 创建WebSocket服务
@@ -44,21 +46,33 @@ function initWebSocket(server) {
// 保存连接
addConnection(username, ws);
// 通知所有在线用户当前在线用户列表
broadcast({
type: "userOnline",
userList: getOnlineUsers()
});
// 接收客户端消息
ws.on("message", (message) => {
try {
const data = JSON.parse(message.toString());
console.log("收到WebSocket消息:", data);
try {
const data = JSON.parse(message.toString());
console.log("收到WebSocket消息:", data);
handleMessage(username, data);
} catch (error) {
console.error("WebSocket消息处理失败:", error);
}
});
handleMessage(username, data);
} catch (error) {
console.error("WebSocket消息处理失败:", error);
}
});
// 连接关闭
ws.on("close", () => {
removeConnection(username);
// 通知所有在线用户当前在线用户列表
broadcast({
type: "userOnline",
userList: getOnlineUsers()
});
});
// WebSocket错误
@@ -121,7 +135,6 @@ function handleSendMessage(senderName, data) {
message: "消息保存失败"
})
);
}
return;
}