This repository has been archived by the owner on Jul 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
80 lines (68 loc) · 1.76 KB
/
server.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
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3001 });
let users = {};
// Remove the socket information from every user before sending as it cannot be stringified due to circular structure
const getUsersWithoutSocket = users => {
return Object.entries(users).reduce((accumulator, user) => {
accumulator[user[0]] = { name: user[1].name };
return accumulator;
}, {});
};
// Broadcast to every open socket except my own
const broadcast = (data, ws) => {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN && client !== ws) {
client.send(JSON.stringify(data));
}
});
};
wss.on('connection', ws => {
let i = 0;
ws.on('message', message => {
const data = JSON.parse(message);
switch (data.type) {
case 'ADD_USER': {
i = Object.keys(users).reduce(function(a, b) {
return Math.max(a, b);
}, 0);
users = { ...users, [i + 1]: { name: data.name, ws: ws } };
const usersWithoutSocket = getUsersWithoutSocket(users);
const updateUserAction = {
type: 'UPDATE_USERS',
users: usersWithoutSocket
};
ws.send(JSON.stringify(updateUserAction));
broadcast(updateUserAction, ws);
break;
}
case 'ADD_MESSAGE':
broadcast(
{
type: 'ADD_MESSAGE',
user: data.user,
content: data.content
},
ws
);
break;
default:
break;
}
});
ws.on('close', () => {
// Find the user who belongs to the now closed socket
const userToRemove = Object.entries(users).filter(
user => user[1].ws === ws
);
const removeIndex = userToRemove ? userToRemove[0][0] : null;
if (removeIndex) delete users[removeIndex];
const usersWithoutSocket = getUsersWithoutSocket(users);
broadcast(
{
type: 'UPDATE_USERS',
users: usersWithoutSocket
},
ws
);
});
});