-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
32 lines (25 loc) · 889 Bytes
/
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
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
import WebSocket, { WebSocketServer } from 'ws';
// Simple websocket server
// This server acts like echo for all the connected clients
const wss = new WebSocketServer({ port: 8080 });
console.log('Server up');
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
const messageData = JSON.parse(message);
console.log('received: ', messageData);
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(messageData));
};
});
});
ws.send(
JSON.stringify({
type: 'text',
sent_by: 'WS Server',
text: 'Connected successfully',
sent_at: Date.now(),
})
);
});