使用 dgram 发送消息的固定端口

Fixed port for sending messages with dgram

我正在使用节点 dgram 将 OSC 消息发送到设备。 设备将其响应发送到请求来自的端口(我无法更改此设置)。

现在我的问题是我不知道 dgram 将使用哪个端口发送消息,所以我无法绑定 UDP 套接字以监听正确的端口以获取响应。

有什么方法可以强制 dgram 每次都从预先确定的端口发送吗?

编辑:添加代码

var serverPorts = {
  ClientSide: 1488,
  ControllerSide: 1499
};

// UDP server, listens to controllers.
var dgram = require("dgram");
var UDPserver = dgram.createSocket("udp4");
const OSC = require("osc-js");
// socket.io, listening to K2
var SocketServer = require("socket.io").listen(serverPorts.ClientSide);

// Got messages on the server
UDPserver.on("message", function(msg, rinfo) {
  console.log(
    "server got: " + msg + " from " + rinfo.address + ":" + rinfo.port
  );
  // Send them to the K2 clients
  console.log("emitting on osc: " + msg);
  SocketServer.sockets.emit("osc", { osc: msg });
});

UDPserver.on("listening", function() {
  var address = UDPserver.address();
  console.log(
    "UDP server listening on " + address.address + ":" + address.port
  );
});

UDPserver.bind(serverPorts.ControllerSide);

SocketServer.sockets.on("connection", function(socket) {
  // Tell who we are and our version
  socket.emit("admin", { id: "K2OSCSERVER", version: 0.1 });
  console.log("Emitted ID and version on the admin channel");

  // K2 sent us OSC data
  socket.on("osc", function(data) {
    console.log("Received data on the 'osc' channel: " + data);
    // Send data on each one of the UDP hosts
    var message =
      typeof data.value != "undefined" && data.value != null
        ? new OSC.Message(data.path, data.value)
        : new OSC.Message(data.path);
    var binary = message.pack();
    var buffer = new Buffer.from(binary, "binary");
    var client = dgram.createSocket("udp4");
    client.send(buffer, 0, buffer.length, 10024, "192.168.0.171", function(
      err,
      bytes
    ) {
      console.log("err: ", err, "bytes: ", JSON.stringify(bytes));
      //client.close();
    });
  });
});

Is there any way to force dgram to send from a pre-determined port everytime?

只需将 UDP 套接字绑定到您要用作源端口的端口(和 IP)。当您随后在此套接字上调用 sendsendto 时,它将使用您绑定的地址(IP+端口)作为源地址。然后你可以在同一个套接字上调用 recvrecvfrom 来获得响应。

编辑 - 在看到实际代码后:
问题是您创建了另一个用于发送的 UDP 套接字。相反,您应该使用已经绑定在地址和端口上的套接字,不仅用于接收,还用于发送。