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

时间:2019-01-29 15:04:48

标签: node.js dgrams

我试图通过一个小的客户端/服务器示例来理解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();
});

如何使它能够连续不断地发送数据包?

1 个答案:

答案 0 :(得分:0)

在操作结束之前,您正在关闭套接字连接。我可以建议仅在发送完所有消息后才将其关闭,例如:

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