-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
server.js
34 lines (28 loc) · 859 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
33
34
'use strict';
const fs = require('node:fs');
const http = require('node:http');
const WebSocket = require('ws');
const index = fs.readFileSync('./index.html', 'utf8');
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end(index);
});
server.listen(8000, () => {
console.log('Listen port 8000');
});
const ws = new WebSocket.Server({ server });
ws.on('connection', (connection, req) => {
const ip = req.socket.remoteAddress;
console.log(`Connected ${ip}`);
connection.on('message', (message) => {
console.log('Received: ' + message);
for (const client of ws.clients) {
if (client.readyState !== WebSocket.OPEN) continue;
if (client === connection) continue;
client.send(message, { binary: false });
}
});
connection.on('close', () => {
console.log(`Disconnected ${ip}`);
});
});