添加用户在线状态更新
This commit is contained in:
@@ -1,28 +1,46 @@
|
||||
const connections = new Map();
|
||||
const onlineUsers = new Map();
|
||||
|
||||
// 保存用户连接
|
||||
function addConnection(username, ws) {
|
||||
connections.set(username, ws);
|
||||
onlineUsers.set(username, ws);
|
||||
|
||||
console.log(`用户 ${username} 已连接`);
|
||||
console.log("当前在线用户:", [...connections.keys()]);
|
||||
console.log("当前在线用户:", [...onlineUsers.keys()]);
|
||||
}
|
||||
|
||||
// 获取用户连接
|
||||
function getConnection(username) {
|
||||
return connections.get(username);
|
||||
return onlineUsers.get(username);
|
||||
}
|
||||
|
||||
// 删除用户连接
|
||||
function removeConnection(username) {
|
||||
connections.delete(username);
|
||||
onlineUsers.delete(username);
|
||||
|
||||
console.log(`用户 ${username} 已断开`);
|
||||
console.log("当前在线用户:", [...connections.keys()]);
|
||||
console.log("当前在线用户:", [...onlineUsers.keys()]);
|
||||
}
|
||||
|
||||
// 获取所有在线用户
|
||||
function getOnlineUsers() {
|
||||
return Array.from(onlineUsers.keys());
|
||||
}
|
||||
|
||||
// 广播所有在线用户
|
||||
function broadcast(data) {
|
||||
const message = JSON.stringify(data);
|
||||
|
||||
for (const ws of onlineUsers.values()) {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
addConnection,
|
||||
getConnection,
|
||||
removeConnection,
|
||||
getOnlineUsers,
|
||||
broadcast
|
||||
};
|
||||
+22
-9
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user