Created
September 30, 2018 11:10
-
-
Save mStirner/ab62737e3a1b9f21a9259e80b7e9332b to your computer and use it in GitHub Desktop.
UDP Service discover, node.js
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
const dgram = require("dgram"); | |
var client = dgram.createSocket("udp4"); | |
client.on("message", function(data, remote){ | |
let str = data.toString("utf8"); | |
let obj = JSON.parse(str); | |
if(obj.service === "http"){ | |
// we found what we wanted | |
// dont listen on message events anymore | |
client.removeAllListeners("message"); | |
//socket.connect(); remote.address & obj.port | |
} | |
console.log("data from", remote); | |
console.log("data", obj); | |
}); | |
client.on('listening', function(){ | |
let addr = this.address(); | |
console.log("Client waiting for message on %s:%d", addr.address, addr.port) | |
}); | |
client.bind(4512, "255.255.255.255"); |
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
const dgram = require("dgram"); | |
var socket = dgram.createSocket('udp4'); | |
socket.on('listening', function(){ | |
socket.setBroadcast(true); | |
const message = JSON.stringify({ | |
service: "http", | |
port: 8080 | |
}); | |
setInterval(function(){ | |
console.log("Send messae"); | |
socket.send(message, 0, message.length, 4512, "255.255.255.255"); | |
}, 1000); | |
}); | |
// bind socket to port | |
// we dont need a specific outgoing port | |
socket.bind(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment