Update index.js
Browse files
index.js
CHANGED
|
@@ -8,39 +8,37 @@ const io = new Server(server);
|
|
| 8 |
|
| 9 |
app.use(express.static("public"));
|
| 10 |
|
| 11 |
-
let rooms = {};
|
| 12 |
-
|
| 13 |
io.on("connection", (socket) => {
|
| 14 |
console.log("User connected:", socket.id);
|
| 15 |
|
| 16 |
socket.on("join-room", ({ roomId, name }) => {
|
| 17 |
socket.join(roomId);
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
socket.emit("all-users", rooms[roomId]);
|
| 25 |
});
|
| 26 |
|
| 27 |
-
socket.on("
|
| 28 |
-
io.to(
|
| 29 |
-
|
| 30 |
-
|
| 31 |
});
|
| 32 |
});
|
| 33 |
|
| 34 |
socket.on("disconnect", () => {
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
}
|
| 40 |
}
|
| 41 |
});
|
| 42 |
});
|
| 43 |
|
| 44 |
server.listen(7860, () => {
|
| 45 |
-
console.log("Server running
|
| 46 |
});
|
|
|
|
| 8 |
|
| 9 |
app.use(express.static("public"));
|
| 10 |
|
|
|
|
|
|
|
| 11 |
io.on("connection", (socket) => {
|
| 12 |
console.log("User connected:", socket.id);
|
| 13 |
|
| 14 |
socket.on("join-room", ({ roomId, name }) => {
|
| 15 |
socket.join(roomId);
|
| 16 |
+
socket.name = name;
|
| 17 |
+
socket.roomId = roomId;
|
| 18 |
|
| 19 |
+
socket.to(roomId).emit("message", {
|
| 20 |
+
name: "System",
|
| 21 |
+
text: `${name} joined the room`
|
| 22 |
+
});
|
|
|
|
|
|
|
| 23 |
});
|
| 24 |
|
| 25 |
+
socket.on("send-message", (msg) => {
|
| 26 |
+
io.to(socket.roomId).emit("message", {
|
| 27 |
+
name: socket.name,
|
| 28 |
+
text: msg
|
| 29 |
});
|
| 30 |
});
|
| 31 |
|
| 32 |
socket.on("disconnect", () => {
|
| 33 |
+
if (socket.roomId) {
|
| 34 |
+
socket.to(socket.roomId).emit("message", {
|
| 35 |
+
name: "System",
|
| 36 |
+
text: `${socket.name} left the room`
|
| 37 |
+
});
|
| 38 |
}
|
| 39 |
});
|
| 40 |
});
|
| 41 |
|
| 42 |
server.listen(7860, () => {
|
| 43 |
+
console.log("Server running at http://localhost:3000");
|
| 44 |
});
|