gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:40 25 4
gpt4 key购买 nike

我对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

关于node.js - Node : how to set static port to udp client in node js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52417521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com