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.
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.