-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
83 lines (71 loc) · 2.1 KB
/
server.js
File metadata and controls
83 lines (71 loc) · 2.1 KB
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
83
import express from "express";
import http from "http";
import { Server } from "socket.io";
import { ACTIONS } from "./Actions.js";
import path from "path";
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const __dirname = path.resolve();
const userSocketMap = {};
const getALlConnectedClients = (roomId) => {
return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map(
(socketId) => {
return {
socketId,
username: userSocketMap[socketId],
};
}
);
};
// initialize socket.io
io.on("connection", (socket) => {
console.log("socket connected: " + socket.id);
// Make Join Event
socket.on(ACTIONS.JOIN, ({ roomId, username }) => {
userSocketMap[socket.id] = username;
socket.join(roomId);
const clients = getALlConnectedClients(roomId);
clients.forEach(({ socketId }) => {
// Emit Joined
io.to(socketId).emit(ACTIONS.JOINED, {
clients,
username,
socketId: socket.id,
});
});
});
// disconnecting event
socket.on("disconnecting", () => {
const rooms = [...socket.rooms];
rooms.forEach((roomId) => {
socket.in(roomId).emit(ACTIONS.DISCONNECTED, {
socketId: socket.id,
username: userSocketMap[socket.id],
});
});
delete userSocketMap[socket.id];
socket.leave();
});
// code change event
socket.on(ACTIONS.CODE_CHANGE, ({ roomId, code }) => {
socket.in(roomId).emit(ACTIONS.CODE_CHANGE, { code });
});
// sync code event
socket.on(ACTIONS.SYNC_CODE, ({ socketId, code }) => {
io.to(socketId).emit(ACTIONS.SYNC_CODE, { code });
});
// message event
socket.on(ACTIONS.NEW_CHAT_MESSAGE, ({ roomId, messageObj }) => {
io.to(roomId).emit(ACTIONS.NEW_CHAT_MESSAGE, { messageObj });
});
});
app.use(express.static(path.join(__dirname, "/dist")));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "dist", "index.html"));
});
// listen for incoming connections
const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});