This repository has been archived by the owner on Oct 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
172 lines (153 loc) · 3.61 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080, host: '0.0.0.0' });
console.log('websocket server set up on port 8080');
const maxClients = 8;
let rooms = {};
const generateRoomCode = (length) => {
let roomCode = '';
const characters = 'abcdefghijklmnopqrstuvwxyz';
for (let i = 0; i < length; i += 1) {
roomCode += characters.charAt(
Math.floor(Math.random() * characters.length),
);
}
return roomCode;
};
const createRoom = (ws, params) => {
const roomCode = generateRoomCode(4);
const { name } = params;
rooms[roomCode] = [ws];
ws.roomCode = roomCode;
ws.name = name;
const message = `room created with room code: ${roomCode}. Host's name: ${name}`;
console.info(message);
ws.send(
JSON.stringify({
type: 'info',
params: {
roomCode,
name,
message,
participants: [name],
},
}),
);
};
const joinRoom = (ws, params) => {
const { roomCode, name } = params;
const formattedRoomCode = roomCode.toLowerCase();
if (rooms[formattedRoomCode] == null) {
const message = `room ${formattedRoomCode} does not exist`;
console.warn(message);
ws.send(
JSON.stringify({
type: 'error',
params: {
message,
},
}),
);
return;
}
if (rooms[formattedRoomCode].length >= maxClients) {
const message = `room ${formattedRoomCode} is full`;
console.warn(message);
ws.send(
JSON.stringify({
type: 'error',
params: { message },
}),
);
return;
}
rooms[formattedRoomCode].push(ws);
ws.roomCode = formattedRoomCode;
ws.name = name;
const message = `${name} joined room with room code: ${formattedRoomCode}`;
console.info(message);
const participants = rooms[formattedRoomCode].map(
(participant) => participant.name,
);
ws.send(
JSON.stringify({
type: 'info',
params: {
roomCode: formattedRoomCode,
name,
message,
participants,
},
}),
);
broadcastToRoom(
ws,
JSON.stringify({
type: 'participant joined',
params: {
roomCode: formattedRoomCode,
name,
participants,
},
}),
);
};
const leaveRoom = (ws) => {
const { roomCode } = ws;
rooms[roomCode] = rooms[roomCode]?.filter((s) => s !== ws) ?? undefined;
console.info(`user left room ${roomCode}`);
broadcastToRoom(
ws,
JSON.stringify({
type: 'participant left',
params: {
roomCode,
participants:
rooms[roomCode]?.map((participant) => participant.name) ?? [],
},
}),
);
if (rooms[roomCode]?.length === 0) {
delete rooms[roomCode];
console.info(`deleted room ${roomCode}`);
}
};
const broadcastToRoom = (ws, data) => {
const { roomCode } = ws;
console.info(`broadcasting message to room ${roomCode}: ${data}`);
rooms[roomCode]?.forEach((client) => client.send(data));
};
wss.on('connection', (ws) => {
ws.on('message', (data) => {
try {
const obj = JSON.parse(data);
const { type, params } = obj;
switch (type) {
case 'create':
createRoom(ws, params);
break;
case 'join':
joinRoom(ws, params);
break;
case 'leave':
leaveRoom(ws);
break;
default:
broadcastToRoom(ws, JSON.stringify(obj));
break;
}
} catch (error) {
console.error(error);
}
});
ws.on('close', () => {
leaveRoom(ws);
});
ws.send(
JSON.stringify({
type: 'info',
params: {
message: 'connected!',
},
}),
);
});