Skip to content

Instantly share code, notes, and snippets.

@andrew-aladev
Last active October 25, 2016 14:50
Show Gist options
  • Save andrew-aladev/18fb365e3934b1e71d030bdec1ac09f5 to your computer and use it in GitHub Desktop.
Save andrew-aladev/18fb365e3934b1e71d030bdec1ac09f5 to your computer and use it in GitHub Desktop.
ssdp test
"use strict";
process
.once('uncaughtException', function (error) {
console.error(
'uncaught exception, error: \'%s\', stack: \'%s\'',
error.toString(), error.stack
);
process.exit(1);
})
.once('unhandledRejection', function (error, p) {
console.error(
'uncaught promise rejection, error: \'%s\', stack: \'%s\'',
error.toString(), error.stack
);
process.exit(2);
})
.once('exit', function (code, signal) {
console.log('process exited, code: \'%s\', signal: \'%s\'', code, signal);
});
var MULTICAST_HOST = '239.255.255.250';
var HOST = '0.0.0.0';
var PORT = '1900';
var PREFIX = 'multicastApp::';
var TTL = 1;
var uuid = require('node-uuid');
var dgram = require('dgram');
var id = uuid.v4();
var socket = dgram.createSocket('udp4');
function startSendingData() {
var index = 0;
function sendData() {
var data = new Buffer(
PREFIX + JSON.stringify(
{
id : id,
index : index
}
)
);
index++;
// console.log('sending data');
socket.send(data, 0, data.length, PORT, MULTICAST_HOST, function () {
// console.log('sent data');
});
}
sendData();
setInterval(sendData, 1000);
}
socket
.on('error', function (error) {
console.error('received error: \'%s\'');
})
.on('message', function (data) {
data = data.toString();
if (data.indexOf(PREFIX) !== 0) {
// console.log('received data from another application');
return;
}
data = data.substring(PREFIX.length);
try {
data = JSON.parse(data);
} catch (error) {
console.error('error parsing data: \'%s\'', error);
}
if (data.id === id) {
// console.log('received my data');
} else {
console.log('received data, id: \'%s\', index: \'%s\'', data.id, data.index);
}
})
.on('listening', function () {
var address = socket.address();
console.info('socket is listening, address: \'%s\'', JSON.stringify(address));
socket.addMembership(MULTICAST_HOST);
socket.setMulticastTTL(TTL);
})
.bind(PORT, HOST, function () {
console.info('socket bound');
startSendingData();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment