-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
33 lines (24 loc) · 828 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
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('open', function open() {
console.log('connected');
});
server.on('close', function close() {
console.log('disconnected');
});
server.on('connection', function connection(ws, req) {
const ip = req.connection.remoteAddress;
const port = req.connection.remotePort;
const clientName =port;
console.log('%s is connected', clientName)
ws.on('error', () => console.log('errored'));
ws.on('message', function incoming(message) {
console.log('received: %s from %s', message, clientName);
// boardcast to all the users
server.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(clientName+"@"+message);
}
});
});
});