user1179299 user1179299 - 7 days ago 8
Node.js Question

nodejs + express : make http request wait for udp response

I am a nodejs web(express) application, when someone(UI) sends a get request to me ,I send a udp request to another guy and expect a reply from him, and when the udp server(part of me) receives the reply from him, I sent it back as httpresponse to the the guy who sent me httpget request.


  1. how to make httprequest wait until a udp response received?

  2. how to set communication between udp server and my controller/action method which has got a httpget request.



I have tried 'setTimeOut' function, but request doesn't wait for it.

I am calling this sendMessage from the my controller/action:

module.exports.sendMessage = function (ip, port, message) {
var msg = new Buffer(message);
var dgram = require('dgram');
var client = dgram.createSocket('udp4');

client.send(msg, 0, msg.length, port, ip, function (err, bytes) {
if (err)
throw err;
console.log('UDP message sent to ' + ip + ':' + port);
client.close();
});
}


controller/action code:

router.get('/getSomething', function (req, res) {
//calls send message from here
}


udp server code which runs at all time from the time application started:

server.on('message', function (message, remote) {
console.log(remote.address + ':' + remote.port + ' - ' + message + message.length);
}


Thanks.

Answer

You can change your code to

module.exports.sendMessage = function (ip, port, message, res) {
    var msg = new Buffer(message);
    var dgram = require('dgram');
    var client = dgram.createSocket('udp4');

    client.send(msg, 0, msg.length, port, ip, function (err, bytes) {
        if (err)
            throw err;
        console.log('UDP message sent to ' + ip + ':' + port);
    });

    client.on('message', function(msg, rinfo) {
      client.close();
      res.send(msg);
    });
}

And you can call it like

router.get('/getSomething', function (req, res) {
  sendMessage('x', 'z', 'y', res);
}
Comments