0

I am developing a node.js program that connects over UDP with another program running on the same machine. Currently I am sending data like this:

import dgram = require("dgram");
const client = dgram.createSocket("udp4");

//Some code to structure the message how the server wants it
const message = Buffer.alloc(413);
message.write("TEST\0");

client.send(message, 0, message.length, 49000, '127.0.0.1', (err) => {
    if (err) {
        this.client.close();
        console.error(err);
    }
});

This works fine, however, I want to do the code in two steps. First open the connection, and then send the message. This is the code that I wrote (skipping some repeted things):

//const message same as above

this.client.bind(49000, '127.0.0.1', (err) => {
    if (err) {
        this.client.close();
        console.error(err);
    } else {
        this.client.send(message, 0, message.length, (err) => {
            if (err) {
                this.client.close();
                console.error(err);
            }
        });
    }
});

This throws the error: throw new ERR_SOCKET_BAD_PORT(name, port, allowZero); RangeError [ERR_SOCKET_BAD_PORT]: Port should be > 0 and < 65536. Received 0.

Edit:

Thanks leitning! .connect() is exactly what I needed. I now have another issue. When I do .send() directly without calling .connect() before I can receive incoming datagrams by creating a .on('message') listener on the client. But when I connect and then send, the listener doesn't receive any incoming messages. I tested this with Wireshark and there are incoming messages.

The code is:

import dgram = require("dgram");
const client = dgram.createSocket("udp4");

const message = Buffer.alloc(413);
message.write("TEST\0");

client.connect(49000,'127.0.0.1',err => {
    if (err) console.error(err);
    client.send(message, 0, message.length, 49000, '127.0.0.1', (err) => {
        if (err) {
            this.client.close();
            console.error(err);
        }
    });
});
client.on('message',(data) => {
    console.log(data);
});

Is there something I missed from the docs as to how to receive messages after doing .connect() ?

1 Answers1

0

When you bind a port you are claiming that port from the operating system for the purposes of sending from and receiving to. It does not have anything to do with where your messages will be sent to.

By binding to localhost:49000, packets that you send will declare that they from localhost port 49000. You can also then listen to the bound socket for incoming messages to localhost port 49000.

You still need to declare a recipient for messages that you are trying to send. You get an invalid port error because the function is interpreting your 0 argument as the destination port. dgram.send docs

It looks like the functionality you are trying to use is covered in the dgram.connect method.

leitning
  • 1,081
  • 1
  • 6
  • 10