-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
43 lines (38 loc) · 1.25 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
const WebSocket = require('ws');
const express = require('express');
const app = express();
const server = app.listen(process.env.PORT || 3000);
const wss = new WebSocket.Server({ server });
const SEND_FILE_OPTIONS = {
root: __dirname + "/public/"
};
wss.on('connection', function connection (ws){
ws.on('message', function message(data){
wss.clients.forEach(function each(client){
if(client.readyState === WebSocket.OPEN){
client.send(JSON.stringify({
'type': 'USER_MESSAGE',
'message': JSON.parse(data)
}));
}
});
});
console.log(`new user connected. total users: ${wss.clients.size}`);
wss.clients.forEach(updateLiveCount);
ws.on('close', function close(){
wss.clients.forEach(updateLiveCount);
console.log(`user disconnected. total users: ${wss.clients.size}`);
})
});
function updateLiveCount(client){
if(client.readyState === WebSocket.OPEN){
client.send(JSON.stringify({
'type': 'USER_COUNT',
'count': wss.clients.size
}));
}
}
app.use(express.static(__dirname + "/public/"));
app.get('/', (req, res) => {
res.sendFile('index.html', SEND_FILE_OPTIONS);
});