You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

48 lines
1.2 KiB

const WebSocket = require('ws');
const DEBUG = (process.env.NODE_ENV !== "production");
const Messenger = function() {
this.clients = {};
};
Messenger.prototype.messageOne = function(ws, message) {
DEBUG && console.log(`Sending to only ${ws.id}:`);
DEBUG && console.log(message);
ws.send(JSON.stringify(message));
};
Messenger.prototype.messageOthers = function(ws, message) {
DEBUG && console.log(`Sending to other client(s):`);
DEBUG && console.log(message);
Object.values(this.clients).forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
};
Messenger.prototype.messageAll = function(message) {
const clients = Object.values(this.clients);
DEBUG && console.log(`Sending to all ${clients.length} client(s):`);
DEBUG && console.log(message);
clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(message));
}
});
};
Messenger.prototype.subscribe = function(ws) {
this.clients[ws.id] = ws;
};
Messenger.prototype.unsubscribe = function(ws) {
delete this.clients[ws.id];
};
module.exports = Messenger;