Node.js UDP client to handle a response from a udp server

16,577

Just stumbled across the question so I thought I'd pipe in with an answer:

In your client.send function, calling client.close(); will close the UDP connection between your server and the client. Therefore, if you want to listen for messages, you should not call that immediately after you send your message.

Secondly, loganfsmyth's comment provided some good advice - you should add your event handlers first, then send the message.

In the end, this was the changed code needed to get your scenario working

var client = dgram.createSocket('udp4');

client.on('listening', function () {
    var address = client.address();
    console.log('UDP Server listening on ' + address.address + ":" + address.port);
});

client.on('message', function (message, remote) {

    console.log(remote.address + ':' + remote.port +' - ' + message);

});

client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {

    if (err) throw err;
    console.log('UDP message sent to ' + HOST +':'+ PORT);

});
Share:
16,577

Related videos on Youtube

C graphics
Author by

C graphics

Updated on September 15, 2022

Comments

  • C graphics
    C graphics over 1 year

    I am trying to write an app in node.js to send a udp request to a device ( which has udp server) and then receive the response and display it. The device acts in such a way that upon receipt of a request on its port 11220 it returns a response immediately.

    The code below sends a udp request to the device and the device responses back immediately ( I can see it in wireshark) but I can not handle/display the revived message. Or at least I just want to be able to display a message upon receipt of a reply from the device. Please let me know what is missing in my code or show me a complete code to do it. Very much appreciated.

    As well, I do not prefer to use socket.io etc.

    var PORT = 11220 ;
    var HOST = '192.168.1.111';
    
    var dgram = require('dgram');
    var message = new Buffer(9);
    var client = dgram.createSocket('udp4');
    client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
        if (err) throw err;
        console.log('UDP message sent to ' + HOST +':'+ PORT);
        client.close();
    
    });
    
    
    client.on('listening', function () {
        var address = server.address();
        console.log('UDP Server listening on ' + address.address + ":" + address.port);
    });
    
    client.on('message', function (message, remote) {
        // CAN I HANDLE THE RECIVED REPLY HERE????
        console.log(remote.address + ':' + remote.port +' - ' + message);
    
    });