-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.js
More file actions
37 lines (25 loc) · 895 Bytes
/
index.js
File metadata and controls
37 lines (25 loc) · 895 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
26
27
28
29
30
31
32
33
34
35
36
37
/**
* A minimal WebSockets server in node
* using https://github.com/websockets/ws
*/
import express from 'express';
import { WebSocket, WebSocketServer } from 'ws';
import { v4 as uuidv4 } from 'uuid';
const PORT = process.env.PORT || 3000;
const server = express()
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const wss = new WebSocketServer({ server });
wss.on('connection', (ws) => {
const uuid = uuidv4();
console.log(`[${uuid}] Client connected`);
ws.on('close', () => console.log(`[${uuid}] Client disconnected`));
ws.on('message', (message) => {
console.log(`[${uuid}] Received message: ${message}`);
// Broadcast to everyone else.
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});