Skip to content

Instantly share code, notes, and snippets.

@avishnyak
Created June 1, 2016 16:06
Show Gist options
  • Save avishnyak/c72cddf768610b3af353df023aae3fd1 to your computer and use it in GitHub Desktop.
Save avishnyak/c72cddf768610b3af353df023aae3fd1 to your computer and use it in GitHub Desktop.
Multicast-Manager
var net_manager = require('./net_manager');
net_manager.withSocket(function (api) {
return api.broadcast('This is a test')
.then(api.unbind);
});
var promise = require('bluebird');
var dgram = require('dgram');
function getSocket(port, multicastAddress) {
return new promise(function (resolve, reject) {
try {
var socket = dgram.createSocket({type: 'udp4', reuseAddr: true});
socket._port = port;
socket.once('listening', function () {
socket._multicastAddress = multicastAddress || '224.0.2.1';
socket.setBroadcast(true);
socket.setMulticastLoopback(true);
socket.setMulticastTTL(1);
socket.addMembership(socket._multicastAddress);
resolve(socket);
});
socket.bind(socket._port);
} catch (ex) {
reject(ex);
}
}).disposer(function (socket, promise) {
if (socket._handle) {
socket.close();
}
});
}
exports.withSocket = function bind(port, multicastAddress, callback) {
var p = typeof port === 'number' ? port : 61088;
var cb = typeof port === 'function' ? port : callback;
return promise.using(getSocket(p, multicastAddress), function (socket) {
var api = {
broadcast: broadcast.bind(socket),
/*
... other high-level protocol functions here
*/
unbind: unbind.bind(socket)
};
return promise.try(cb, api);
});
};
function broadcast(message) {
var socket = this;
var messageBuffer = new Buffer(message);
return promise.fromCallback(function (callback) {
socket.send(messageBuffer, 0, messageBuffer.length, socket._port, socket._multicastAddress, callback);
});
}
function unbind() {
var socket = this;
return promise.fromCallback(function (callback) {
socket.close(callback);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment