Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you have to close a UDP (dgram) client in Node.js or can you reuse it?

The docs (and a number of libraries I've looked at) seem to indicate that you close the client every time you send:

var dgram = require('dgram');
var message = new Buffer("Some bytes");
var client = dgram.createSocket("udp4");
client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {
  client.close();
});

I don't really know much about the inner workings of UDP to be honest, but what would stop you from just reusing the client each time you want to send a UDP packet? Do you have to close() it?

I've tested it on localhost (that is, reusing the client), and it sends multiple packets fine (at least to the same destination), but that's not really enough of a test to assure me that it would be ok in the big wide world out there.

The source of send() calls a _startReceiving() function, which "binds to a random port", and then "starts receiving" - but I'm unclear as to what should be receiving here, because we're actually sending. In any case, it's enough to make me think that there could be issues with keeping a client around... I'm just not sure what they are.

like image 651
Michael Hart Avatar asked Nov 26 '25 14:11

Michael Hart


2 Answers

You can reuse a udp socket for multiple requests. For example this behavior is also seen in multiple tests: https://github.com/joyent/node/blob/master/test/simple/test-dgram-pingpong.js

The udp socket binds to a random port, because it has to specify a source address with port.

like image 159
Skomski Avatar answered Nov 29 '25 03:11

Skomski


You need to close the UDP socket in 3 cases:

  1. You are going to create another socket bound to the same local port, thus avoiding port in use issues.
  2. Your peer is using your local port to respond to, and you no longer want those responses.
  3. Your peer is using your local port as an identifier, and you no longer want to be associated with it.
like image 21
Steven Spungin Avatar answered Nov 29 '25 02:11

Steven Spungin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!