-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.utils.js
39 lines (31 loc) · 1.15 KB
/
server.utils.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
function initializeListeners(socket, { users, userNames }) {
socket.on("join-request", ({ name }) => {
if (userNames[name]) {
socket.emit("nick-already-used", { name });
} else {
socket.emit("join-success", { name });
}
});
socket.on("new-user", ({ name }) => handleNewUserConnection(name, socket));
socket.on("send-chat-message", (msg) => handleSendMessage(msg, socket));
socket.on("disconnect", () => {
socket.broadcast.emit("user-disconnected", users[socket.id]);
const username = users[socket.id];
console.log(`User called '${username}' has left the chat.`);
delete userNames[username];
delete users[socket.id];
});
function handleSendMessage(message, socket) {
socket.broadcast.emit("chat-message", {
message,
name: users[socket.id],
});
}
function handleNewUserConnection(name, socket) {
console.log("New user", name);
users[socket.id] = name;
userNames[name] = name;
socket.broadcast.emit("user-connected", name);
}
}
module.exports = { initializeListeners };