Skip to content

Instantly share code, notes, and snippets.

@japboy
Last active August 29, 2015 13:57
Show Gist options
  • Save japboy/9594488 to your computer and use it in GitHub Desktop.
Save japboy/9594488 to your computer and use it in GitHub Desktop.
Yet another WebSocket broadcasting server.
#!/usr/bin/env node
'use strict';
var ws, wss, specified, prev, host='0.0.0.0', port=8000;
ws = require('ws');
process.argv.forEach(function (val, i) {
var addr = '0.0.0.0:8000';
if ('-S' === val) {
specified = true;
prev = i;
}
if (specified && i - 1 === prev) {
addr = val;
host = addr.split(':')[0];
port = parseInt(addr.split(':')[1]);
}
});
wss = new ws.Server({ host: host, port: port });
function done (err) {
if (err && err instanceof Error) throw err;
}
wss.broadcast = function (data, callback) {
for (var i in this.clients) this.clients[i].send(data, callback);
console.log('message broadcasted at %s.', (new Date()).toISOString());
};
wss.on('connection', function (sock) {
sock.on('message', function (data) {
console.log('message received at %s.', (new Date()).toISOString());
wss.broadcast(data, done);
});
console.log('client connected at %s.', (new Date()).toISOString());
});
console.log('server launched at %s:%s.', host, port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment