-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
86 lines (75 loc) · 2.34 KB
/
server.js
File metadata and controls
86 lines (75 loc) · 2.34 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
84
85
86
import { createServer } from "node:http";
import next from "next";
import { Server } from "socket.io";
import { ACTIONS } from "./actions.js";
import { socket } from "./src/socket.js";
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();
const userSocketMap = {};
function getAllConnectedClients(roomId, io) {
// Map
return Array.from(io.sockets.adapter.rooms.get(roomId) || []).map(
(socketId) => {
return {
socketId,
username: userSocketMap[socketId],
};
}
);
}
app.prepare().then(() => {
const httpServer = createServer(handler);
const io = new Server(httpServer);
io.on("connection", (socket) => {
console.log("Client connected: ", socket.id);
socket.on("hello", (value) => {
console.log("Received value from client: ", value);
});
socket.on(ACTIONS.JOIN, ({ roomId, username }) => {
console.log("Received value from client: ", username);
userSocketMap[socket.id] = username;
socket.join(roomId);
const allClients = getAllConnectedClients(roomId, io);
allClients.forEach(({ socketId }) => {
io.to(socketId).emit(ACTIONS.JOINED, {
allClients,
username,
socketId: socket.id,
});
});
});
socket.on(ACTIONS.CODE_CHANGE, ({ roomId, value }) => {
socket.in(roomId).emit(ACTIONS.CODE_CHANGE, { value });
});
socket.on(ACTIONS.SYNC_CODE, ({ socketId, code }) => {
io.to(socketId).emit(ACTIONS.SYNC_CODE, code);
});
socket.on(ACTIONS.RUN , ({roomId , output}) =>{
socket.in(roomId).emit(ACTIONS.RUN , {output})
} )
socket.on("disconnecting", () => {
console.log("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();
});
});
httpServer
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});