-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
63 lines (52 loc) · 1.55 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const path = require("path");
const express = require("express");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
app.set("views", "./views");
app.set("io", io);
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use("/css", express.static(path.join(__dirname, "public/css")));
app.use(express.urlencoded({ extended: true }));
const rooms = {};
app.get("/", (req, res) => {
res.render("index", { rooms });
});
app.get("/:room", (req, res) => {
if (rooms[req.params.room] == null) rooms[req.params.room] = { users: {} };
res.render("room", { roomName: req.params.room });
});
server.listen(process.env.PORT || 3000);
io.on("connection", (socket) => {
socket.on("send-chat-message", (room, message) => {
socket.broadcast.to(room).emit("chat-message", {
message,
name: rooms[room].users[socket.id],
});
});
socket.on("new-user", (room, name) => {
socket.join(room);
rooms[room].users[socket.id] = name;
socket.broadcast.to(room).emit("user-connected", name);
});
socket.on("disconnect", () => {
getUserRoom(socket).forEach((room) => {
socket.broadcast
.to(room)
.emit("user-disconnected", rooms[room].users[socket.id]);
delete rooms[room].users[socket.id];
});
});
});
function getUserRoom(socket) {
return Object.entries(rooms).reduce((names, [name, room]) => {
if (room.users[socket.id] != null) names.push(name);
return names;
}, []);
}