无法在节点js中发送多个UDP消息

Cannot send multiple UDP messages in node js

我试图通过 client/server 的一个小例子来理解 dgram。但是,我似乎只能向客户端的每个 运行 发送 1 条消息。如果我尝试像下面的客户端代码一样发送多条消息,则不会发送任何消息。

服务器代码:

var PORT = 16501;
var HOST = '127.0.0.1';

var dgram = require('dgram');
var server = dgram.createSocket('udp4');

server.on('listening', function () {
    var address = server.address();
    console.log('UDP Server: ' + address.address + ":" + address.port);
});

server.on('message', function (message, remote) {
    console.log('Received: ' + remote.address + ':' + remote.port +' - ' + message);

});

server.bind(PORT, HOST);

客户代码:

var PORT = 16501;
var HOST = '127.0.0.1';

var dgram = require('dgram');

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

var i;

for(i=0;i<10;i++) {
    client.send('Test Message', 0, 12, PORT, HOST, function(err, bytes) {
        if (err) throw err;
        console.log('Send: ' + HOST +':'+ PORT);
    });
}
client.close();

此客户端代码有效,但只能发送 1 条消息。

var PORT = 16501;
var HOST = '127.0.0.1';

var dgram = require('dgram');

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

client.send('Test Message', 0, 12, PORT, HOST, function(err, bytes) {
    if (err) throw err;
    console.log('Send: ' + HOST +':'+ PORT);
    client.close();
});

如何让它可以一个接一个地连续发送数据包?

您正在操作结束前关闭套接字连接。我可以建议仅在发送所有消息后关闭它的标志,例如:

var totalReq = 10;
for (var i = 0; i < totalReq; i++) {
    sendMessage(i, totalReq);
}

function sendMessage(index, total) {
    client.send('Test Message', 0, 12, PORT, HOST, function(err, bytes) {
        if (err) throw err;
        console.log('Send: ' + HOST + ':' + PORT);
        // close the connection only after the last request
        if (index == total - 1) {
            client.close();
        }
    });
}