Files
ClassContent/项目合集/聊天室/app版本/代码/backend/socket.js
2024-09-27 02:06:13 +08:00

88 lines
2.3 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 { createServer } = require("http");
const { Server } = require("socket.io");
const httpServer = createServer();
const io = new Server(httpServer);
// 保存群列表
var GroupList = {};
// 保存聊天记录
var HistoryList = {};
io.on("connection", (socket) => {
console.log("a user connected", socket.id);
socket.on("UserLogin", (res) => {
// 如果已经有房间了
if (GroupList.hasOwnProperty(res.room)) {
console.log("1 如果已经有房间了");
// 判断房间是否已经有这个用户名了
var isHave = GroupList[res.room].filter((v) => {
return v.name == res.name;
});
// 没有这个用户
if (isHave.length == 0) {
console.log("2 没有这个用户");
// 将用户加入房间数组
GroupList[res.room].push({
name: res.name,
img: res.img,
});
socket.emit("LoginSuccess", res);
} else {
console.log("3 有这个用户");
socket.emit("UserAlready", "用户名已存在,请改名!");
}
} else {
console.log("4 没有房间");
GroupList[res.room] = [];
// 将用户加入房间数组
GroupList[res.room].push({
name: res.name,
img: res.img,
});
socket.emit("LoginSuccess", res);
}
});
socket.on("JoinRoom", (res) => {
// 将当前 socket 加入群聊
socket.join(res.room);
// 向房间内的所有人发送欢迎信息
io.in(res.room).emit("WelcomeUser", `${res.name} 加入群聊`);
io.in(res.room).emit("RoomOnline", GroupList[res.room]);
});
socket.on("SendMessage", (res) => {
console.log("后端收到的消息为:", res);
socket.to(res.room).emit("SetMessage", res);
});
socket.on("Shake", (res) => {
console.log("Shake");
socket.to(res.room).emit("StartShake", true);
});
socket.on("UserDisconnect", (res) => {
console.log("有个客户端掉线了");
if (GroupList.hasOwnProperty(res.room)) {
console.log("===============");
GroupList[res.room] = GroupList[res.room].filter((v) => {
return v.name != res.name;
});
io.in(res.room).emit("WelcomeUser", `${res.name} 离开群聊`);
// 更新在线人数
io.in(res.room).emit("RoomOnline", GroupList[res.room]);
}
});
});
httpServer.listen(3000);