-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.js
64 lines (53 loc) · 1.75 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
64
const express = require("express");
const app = express();
const port = 3000;
const http = require("http").createServer(app);
const io = require("socket.io")(http);
app.use(express.static(__dirname + "/public"));
app.get("/", (req, res) => res.sendFile(__dirname + "/index.html"));
const rooms = {};
io.on("connection", (socket) => {
console.log("A user connected..");
socket.on("createRoom", (roomId, username) => {
if (!rooms[roomId]) {
rooms[roomId] = [];
rooms[roomId].push(username);
socket.join(roomId);
socket.roomId = roomId;
socket.username = username;
io.to(roomId).emit("roomUsers", rooms[roomId]);
console.log(`${username} created ${roomId}`);
}
});
socket.on("joinRoom", (roomId, username) => {
if (rooms[roomId]) {
rooms[roomId].push(username);
socket.join(roomId);
socket.roomId = roomId;
socket.username = username;
io.to(roomId).emit("roomUsers", rooms[roomId]);
console.log(`${username} joined room ${roomId}`);
} else {
socket.emit("errorMessage", "Room not found.");
}
});
socket.on("message", (msg) => {
const roomId = socket.roomId;
if (roomId) {
socket.broadcast.to(roomId).emit("messageToRoom", {
// Corrected event name
user: socket.username,
message: msg.message, // Fixed to send message content
});
}
});
socket.on("disconnect", () => {
const roomId = socket.roomId;
if (roomId) {
rooms[roomId] = rooms[roomId].filter((user) => user !== socket.username);
io.to(roomId).emit("roomUsers", rooms[roomId]);
console.log(`${socket.username} disconnected from ${roomId}`);
}
});
});
http.listen(port, () => console.log(`Example app listening on port ${port}!`));