Last active
July 31, 2017 01:11
-
-
Save ironman9967/f889fc2c8f80c5e9b6d4e533ded9e002 to your computer and use it in GitHub Desktop.
udp poc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dgram from 'dgram' | |
const procId = process.argv[2] | |
const myPort = process.argv[3] | |
const theirPort = process.argv[4] | |
if (!procId) { | |
throw new Error("must supply a procId as the first argument") | |
} | |
if (!myPort) { | |
throw new Error("must supply a port to host a udp end point as the second argument") | |
} | |
if (!theirPort) { | |
throw new Error("must supply a port to another host a udp end point as the second argument") | |
} | |
const log = msg => console.log(`PROCESS ID[${procId}]: ${msg}`) | |
const udpsk = dgram.createSocket('udp4') | |
udpsk.on('error', err => { | |
log(`udpsk error:\n${err.stack}`) | |
udpsk.close() | |
}) | |
udpsk.on('message', (msg, rinfo) => { | |
log(`udpsk got: ${msg} from ${rinfo.address}:${rinfo.port}`) | |
}) | |
udpsk.on('listening', () => { | |
udpsk.setBroadcast(true) | |
const address = udpsk.address(); | |
log(`udpsk listening ${address.address}:${address.port}`) | |
}) | |
udpsk.bind(myPort) | |
console.log(`PID: ${process.pid}`) | |
const i = setInterval(() => { | |
udpsk.send(`hello from process ${procId}`, theirPort, '255.255.255.255', err => { | |
if (err) { | |
console.error(err) | |
} | |
else { | |
log('message broadcast') | |
} | |
}) | |
}, 5000) | |
process.once('SIGINT', () => { | |
clearInterval(i) | |
console.log('closing udpsk...') | |
udpsk.close() | |
console.log('done') | |
process.exit(0) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "udp-poc", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1", | |
"start": "babel src --out-dir dist && node dist/index.js" | |
}, | |
"keywords": [], | |
"author": "", | |
"license": "ISC", | |
"devDependencies": { | |
"babel-cli": "^6.24.1", | |
"babel-preset-env": "^1.6.0" | |
}, | |
"babel": { | |
"presets": [ | |
[ | |
"env", | |
{ | |
"targets": { | |
"node": "current" | |
} | |
} | |
] | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment