Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 205
Gergely Avatar asked Nov 29 '18 13:11

Gergely


1 Answers

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();
});
like image 160
user846016 Avatar answered Oct 21 '22 08:10

user846016