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