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

Ger*_*ely 4 sockets udp node.js dgrams

我尝试了各种版本的 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();
Run Code Online (Sandbox Code Playgroud)

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

Nodejs 的 dgram 发送文档

socket.send(msg[, offset, length], port[, address][, callback])
Run Code Online (Sandbox Code Playgroud)

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

use*_*016 8

尝试在发送的最后一条消息的回调中关闭套接字。然后,套接字仅在消息已发送时关闭。

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();
});
Run Code Online (Sandbox Code Playgroud)