-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
25 lines (25 loc) · 760 Bytes
/
index.js
File metadata and controls
25 lines (25 loc) · 760 Bytes
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
import { createServer } from 'http';
import staticHandler from 'serve-handler';
import ws, { WebSocketServer } from 'ws';
//serve static folder
const server = createServer((req, res) => { // (1)
return staticHandler(req, res, { public: 'public' })
});
const wss = new WebSocketServer({ server }) // (2)
wss.on('connection', (client) => {
console.log('Client connected !')
client.on('message', (msg) => { // (3)
console.log(`Message:${msg}`);
broadcast(msg)
})
})
function broadcast(msg) { // (4)
for (const client of wss.clients) {
if (client.readyState === ws.OPEN) {
client.send(msg)
}
}
}
server.listen(process.argv[2] || 8080, () => {
console.log(`server listening...`);
})