Files
ClassContent/历届学生/fontendsix/项目练习/上课项目/聊天/backend/index.js
2024-09-27 02:06:13 +08:00

76 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const options = {};
const io = require('socket.io')(options);
// 存放在线的群和群成员
var userOneLine = { };
// 保存群聊天记录
var ChatRecord = {
1001: [
{
userId: '1',
userMessage: ""
}
]
};
io.on('connection', socket => {
socket.on("Login", function(res) {
console.log("Login.....", res);
res.id = returnId();
socket.join(res.roomId);
// 已经存在这个房间了
if (userOneLine.hasOwnProperty(res.roomId)) {
res.type = 2;
userOneLine[res.roomId].push(res);
io.in(res.roomId).emit("system", `欢迎${res.name}加入群聊`);
// 不存在这个群
} else {
// 设置你为群主
res.type = 1;
// 用你的roomId先创建一个空数组
userOneLine[res.roomId] = [];
userOneLine[res.roomId].push(res);
io.in(res.roomId).emit("system", `欢迎您成功创建 ${res.roomId} 群聊`);
}
console.log("userOneLine ==== ", userOneLine);
io.in(res.roomId).emit("SendGroupMembers", userOneLine[res.roomId]);
// socket.emit("success", { title: '我是后端的数据,哈哈哈' });
})
// 接受前端发送过来的聊天内容
socket.on("sendMessage", function(res){
console.log(res);
socket.to(res.roomId).emit("getMessage", res);
})
socket.on("getShake", function(res){
socket.to(res.roomId).emit("sendShake");
})
// 用户离线
socket.on("UserNoLine", function(res){
// 1: 从数组 userOneLine 删除 filter 离线 id 用户
io.in(res.roomId).emit("system", `xx 已离开群聊`);
io.in("room1").emit("SendGroupMembers",userOneLine[res.roomId]);
console.log('用户离线的时候调用,一般做系统通知,');
})
// 用户离线的时候调用,一般做系统通知,
// 通知群内的人,xxx离开群聊了
socket.on('disconnect', (res) => {});
});
function returnId() {
return new Date().getFullYear().toString() + (new Date().getMonth()+1).toString() + new Date().getDate() + new Date().getTime().toString() + Math.random() * new Date().getTime()
}
io.listen(3000);