-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (45 loc) · 1.51 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
const PORT = process.env.PORT || 5192;
const botName = "Code Chat";
const socketio = require("socket.io");
const express = require("express");
const http = require("http");
const path = require("path");
const { userJoin,
getCurrentUser,
userDisconnect,
getUsersInRoom
} = require("./userModules/users");
const formatMsg = require("./userModules/formatMsg");
const index = express();
const server = http.createServer(index);
const io = socketio(server);
index.use(express.static(path.join(__dirname, "assets")));
io.on("connection", function(socket) {
socket.on("joinRoom", function({username, room}) {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
socket.broadcast.to(user.room).emit("message", formatMsg(botName, `${user.username} joined the chat`));
socket.emit("message", formatMsg(botName, `Welcome to Code Chat`));
io.to(user.room).emit("roomUsers", {
room: user.room,
users: getUsersInRoom(room)
});
});
socket.on("chatMessage", function(chatMessage) {
const user = getCurrentUser(socket.id);
io.to(user.room).emit("message", formatMsg(user.username, chatMessage));
});
socket.on("disconnect", function() {
const user = userDisconnect(socket.id);
if(user) {
io.to(user.room).emit("message", formatMsg(botName, `${user.username} left the chat`));
io.to(user.room).emit("roomUsers", {
room: user.room,
users: getUsersInRoom(user.room)
});
}
});
});
server.listen(PORT, function() {
console.log("server initialized at port: ", PORT);
});