如何在 Nodejs 中通过 dgram 发送 UDP 数据包?

How to send a UDP packet via dgram in Nodejs?

我尝试了各种版本的 Nodejs 数据报套接字模块的发送功能:

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

我的服务器确实与另一个客户端一起工作,但这个客户端不行,none 个数据包到达。

Nodejs' dgram send documentation

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

是我填写的参数有问题还是其他原因导致失败?在服务器程序中我确实使用了端口 12000 和环回 IP 地址。

尝试在上次发送消息的回调中关闭套接字。然后,仅当消息发送后套接字才会关闭。

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