节点:如何在节点js中将静态端口设置为udp客户端

Node : how to set static port to udp client in node js

我是 Udp Socket 编程的新手,在这里我实现了连接到 UDP 服务器的 echo UDP 客户端

var buffer = require('buffer');
var udp = require('dgram');
// creating a client socket
var client = udp.createSocket('udp4');

//buffer msg
var data = Buffer.from('Pradip Shinde');

client.on('message',function(msg,info){
  console.log('Data received from server : ' + msg.toString());
  console.log('Received %d bytes from %s:%d\n',msg.length, info.address, info.port);
});

//sending msg
client.send(data,9300,'192.168.1.187',function(error){
  if(error){
    client.close();
  }else{
    console.log('Data sent from client!!!');
  }
}); 

当此客户端向服务器发送消息时,操作系统将随机端口分配给此客户端,但在我的场景中我想要永远不会改变的静态端口,是否可以将静态端口分配给 udp 客户端?

如文档中所述,您可以使用 bind 方法来执行此操作,

For UDP sockets, causes the dgram.Socket to listen for datagram messages on a named port and optional address that are passed as properties of an options object passed as the first argument. If port is not specified or is 0, the operating system will attempt to bind to a random port. If address is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a 'listening' event is emitted and the optional callback function is called.

尝试使用

// Creating a client socket
var client = udp.createSocket('udp4');

// Bind your port here
client.bind({
  address: 'localhost',
  port: 8000,
  exclusive: true
}); 

如需更多信息,请关注此 documentation