56 lines
1.3 KiB
JavaScript
56 lines
1.3 KiB
JavaScript
const WebSocket = require("ws");
|
|
|
|
const onlineUsers = new Map();
|
|
|
|
// 保存用户连接
|
|
function addConnection(username, ws) {
|
|
onlineUsers.set(username, ws);
|
|
|
|
console.log(`用户 ${username} 已连接`);
|
|
console.log("当前在线用户:", [...onlineUsers.keys()]);
|
|
}
|
|
|
|
// 获取用户连接
|
|
function getConnection(username) {
|
|
return onlineUsers.get(username);
|
|
}
|
|
|
|
// 删除用户连接
|
|
function removeConnection(username, ws) {
|
|
const currentWs = onlineUsers.get(username);
|
|
|
|
// 只有 Map 里面存的还是这个连接,才允许删除
|
|
if (currentWs === ws) {
|
|
onlineUsers.delete(username);
|
|
}
|
|
console.log(`用户 ${username} 已断开`);
|
|
console.log("当前在线用户:", [...onlineUsers.keys()]);
|
|
}
|
|
|
|
// 获取所有在线用户
|
|
function getOnlineUsers() {
|
|
return Array.from(onlineUsers.keys());
|
|
}
|
|
|
|
// 广播所有在线用户
|
|
function broadcast(data) {
|
|
const message = JSON.stringify(data);
|
|
|
|
for (const [username, ws] of onlineUsers) {
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
ws.send(message, (error) => {
|
|
if (error) {
|
|
console.error(`向用户 ${username} 广播失败:`, error);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
addConnection,
|
|
getConnection,
|
|
removeConnection,
|
|
getOnlineUsers,
|
|
broadcast
|
|
}; |