Search code examples
node.jssocketsudpdgrams

How to send a UDP packet via dgram in Nodejs?


I tried various versions of Nodejs' datagram socket module's send function:

var dgram = require('dgram');

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

client.send('Hello World!',0, 12, 12000, '127.0.0.1', function(err, bytes) {});
client.send('Hello2World!',0, 12, 12000, '127.0.0.1');
client.send('Hello3World!',12000, '127.0.0.1');

client.close();

My server does work with another client but not this one, none of the packets arrive.

Nodejs' dgram send documentation says

socket.send(msg[, offset, length], port[, address][, callback])

Is my filling in the arguments have a problem or something else make it fail? In the server program I did use port 12000 and the loopback IP address.


Solution

  • Try closing the socket in the callback of the last message sent. Then, the socket gets closed only when the message has got sent.

    var dgram = require('dgram');
    
    var client = dgram.createSocket('udp4');
    
    client.send('Hello World!',0, 12, 12000, '127.0.0.1');
    client.send('Hello2World!',0, 12, 12000, '127.0.0.1');
    client.send('Hello3World!',0, 12, 12000, '127.0.0.1', function(err, bytes) {
    client.close();
    });