3

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.

Michael Hart
  • 5,109
  • 3
  • 22
  • 21

2 Answers2

1

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.

Skomski
  • 4,827
  • 21
  • 30
  • Nice find on the test code! So when does it need to be "closed"? Can you keep it open even if you're sending to different host/ports? Could you just have one "client" open for your entire app? – Michael Hart Jul 19 '12 at 07:06
  • So far I haven't had to explicitly close a client/socket, and have been able to reuse it fine, so I think this answer is correct – Michael Hart Aug 28 '12 at 07:31
  • Hi have you faced the issue with 100% cpu while closing the udp connection when you are using node cluster? https://github.com/joyent/node/issues/7590 – Somnath May 09 '14 at 06:11
1

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.
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78