IXWebSocket/ws/broadcast-server.js

29 lines
733 B
JavaScript
Raw Normal View History

2018-09-27 23:56:48 +02:00
/*
2018-11-14 02:46:05 +01:00
* broadcast-server.js
2018-09-27 23:56:48 +02:00
* Author: Benjamin Sergeant
* Copyright (c) 2017-2018 Machine Zone, Inc. All rights reserved.
*/
const WebSocket = require('ws');
2018-11-14 02:46:05 +01:00
const wss = new WebSocket.Server({ port: 8080, perMessageDeflate: true });
2018-09-27 23:56:48 +02:00
// Broadcast to all.
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
};
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(data) {
// Broadcast to everyone else.
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
});