简体   繁体   中英

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.

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM