Cannot send multiple UDP messages in node js

1.5k Views Asked by At

I am trying to understand dgram with a small example of client/server. However, it seems that I can only send 1 message per run of the client. If I try to send multiple messages like in below client code, nothing gets sent.

Server code:

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

Client code:

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

This client code works but can only send 1 message.

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

How can I make it so that it can send packets one after the other continuously?

1

There are 1 best solutions below

4
BrTkCa On BEST ANSWER

You are closing the socket connection before the operations ends. I can suggest a flag to close it only after all the messages was sent, something like:

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