lephleg
lephleg

Reputation: 1764

Node.js - "Rebind" UDP socket server to a new port

Which is the most efficient way to change a UDP server's listening port on runtime on Node.js?

I have a default port 41234 for my web app but I want the end-user to be able to change this through a settings textbox, which would call the updatePort().

Using the following code the new (neither the old) port isn't actually listening for datagrams, as I cant receive anything.

var SRV_PORT = 41234;
var server = dgram.createSocket("udp4");

server.on("error", function (err) {
  print("server error:\n" + err.stack);
  server.close();
});

server.on("message", function (msg, rinfo) {
  //code for incoming datagram analysis here
});

server.on("listening", function () {
  var address = server.address();
  print("server listening " + address.address + ":" + address.port);
});

//start the UDP server with the default SRV_PORT
server.bind(SRV_PORT);

function updatePort(newPort) {
  server.close();
  server = dgram.createSocket("udp4");
  server.bind(newPort);
}

Upvotes: 0

Views: 1387

Answers (1)

mscdex
mscdex

Reputation: 106746

The reason you wouldn't get any messages after updating the port is because you've assigned a new socket instance to server and do not have any event handlers attached anymore.

Upvotes: 1

Related Questions