Compare commits
2
Commits
74ed1535ed
...
3eb4bfcd5d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3eb4bfcd5d | ||
|
|
4c3b99edac |
+2
-1
@@ -30,7 +30,8 @@ router.get(
|
||||
FROM chat_mysql.contacts c
|
||||
JOIN chat_mysql.users u
|
||||
ON c.contact_name = u.username
|
||||
WHERE c.user_name = ?;
|
||||
WHERE c.user_name = ?
|
||||
ORDER BY contact_name ASC;;
|
||||
`;
|
||||
db.query(sql, [req.user.username], (error, results) => {
|
||||
if (error) {
|
||||
|
||||
@@ -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
|
||||
};
|
||||
+14
-1
@@ -8,6 +8,8 @@ const {
|
||||
addConnection,
|
||||
getConnection,
|
||||
removeConnection,
|
||||
getOnlineUsers,
|
||||
broadcast
|
||||
} = require("./connectionManager");
|
||||
|
||||
// 创建WebSocket服务
|
||||
@@ -44,6 +46,12 @@ function initWebSocket(server) {
|
||||
// 保存连接
|
||||
addConnection(username, ws);
|
||||
|
||||
// 通知所有在线用户当前在线用户列表
|
||||
broadcast({
|
||||
type: "userOnline",
|
||||
userList: getOnlineUsers()
|
||||
});
|
||||
|
||||
// 接收客户端消息
|
||||
ws.on("message", (message) => {
|
||||
try {
|
||||
@@ -59,6 +67,12 @@ function initWebSocket(server) {
|
||||
// 连接关闭
|
||||
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