-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (67 loc) · 2.32 KB
/
index.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const express = require("express");
const socketio = require("socket.io");
const http = require("http");
const path = require("path");
const {
newUser,
formatMessage,
getIndividualRoomUsers,
getActiveUser,
exitRoom
} = require("./helper/helper");
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, "public")));
io.on("connection", (socket) => {
// Listens for a specific event (joinRoom) from the client.
socket.on("joinRoom", ({ username, room }) => {
// New user is creater in Helper File
const user = newUser(socket.id, username, room);
// console.log(`created new user with Socket ID - ${socket.id}`);
// Adds the client to a specific room
socket.join(user.room);
// Sends a message to the client. (Will be Shown to New User Only in Starting)
socket.emit(
"message",
formatMessage("BOT", "Messages are limited to this room")
);
// Sends a message to all clients except the sender.
socket.broadcast
.to(user.room)
.emit(
"message",
formatMessage("BOT", `${user.username} has joined the room`)
);
// Sends a Live Updated Data List to all clients in a specific room.
io.to(user.room).emit("roomUsers", {
room: user.room, // Current Room Name
users: getIndividualRoomUsers(user.room) // All Online User In That Room
});
});
// Listens for a specific event (chatMessage) from the client.
socket.on("chatMessage", (msg) => {
const user = getActiveUser(socket.id);
// console.log(`Active User on Message - ${socket.id}`);
// Sends a message to all clients in a specific room.
io.to(user.room).emit("message", formatMessage(user.username, msg));
});
// Listens for a specific event (chatMessage) from the client.
socket.on("disconnect", () => {
const user = exitRoom(socket.id);
// Sends a message to all clients in a specific room.
io.to(user.room).emit(
"message",
formatMessage("BOT", `${user.username} has left the room`)
);
// Update Room Users to all clients in a specific room.
io.to(user.room).emit("roomUsers", {
room: user.room,
users: getIndividualRoomUsers(user.room)
});
});
});
const PORT = 8000;
server.listen(PORT, () => {
console.log("Server is running");
});