I am tying to redirect a simple UDP broadcast result containing several delayed in (2 sec.) messages from different devices and render the result as a http response. The code bellow is working well and I am able to see the collected broadcast message with the console.log but the web response is allays empty. How to implement this correctly?
var dgram = require("dgram");
var http = require('http');
function broadcast(callback) {
var data = '';
var server = dgram.createSocket("udp4");
server.on("message", function (message, rinfo) {
data += message;
})
server.bind(11000);
var socket = dgram.createSocket("udp4");
socket.bind();
socket.setBroadcast(true);
socket.send(Buffer([3]), 0, 1, 11001, '255.255.255.255', function(err, bytes) {
socket.close();
});
// dealy to collect all messages in 2 sec
setTimeout(function () {
callback(data);
}, 2000);
}
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
broadcast(function(data) {
res.write(data);
console.log(data);
});
res.end();
}).listen(6969, "0.0.0.0");
console.log('HTTP server running at http://0.0.0.0:6969/')
You're calling res.end()
before you've sent data. Move res.end()
into your callback.
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
broadcast(function(data) {
res.write(data);
console.log(data);
res.end();
});
}).listen(6969, "0.0.0.0");