我想在应用程序运行期间保留一个端口,但应用程序不应一直监听该端口。因此,我想将 bind()
调用与 listen()
调用分离。
nodejs中的UDP/Datagram socket有一个bind
函数。但我无法在“普通”(TCP) 套接字 API 中找到它的等效项。
是否可以不监听就绑定(bind)?
最佳答案
您可以创建未包装的 TCP 套接字:
const net = require('net');
const TCP = process.binding('tcp_wrap').TCP;
const socket = new TCP();
// Bind is done here.
socket.bind('0.0.0.0', 3333);
console.log('bound');
// Then, at some later stage, if you want to listen,
// you can use the previously created (and bound) socket.
setTimeout(() => {
console.log('listening');
const server = net.createServer((conn) => {
console.log('got connection');
conn.end('bye\n');
}).listen(socket);
}, 5000);
编辑:要在 Node v9.3.0 及更高版本上实例化套接字,您需要向构造函数传递一个额外的参数:
const TCPWrap = process.binding('tcp_wrap');
const { TCP } = TCPWrap;
const socket = new TCP(TCPWrap.constants.SERVER); // or .SOCKET
不同之处在于使用async_hooks
时能够区分两种类型的套接字。 .
关于node.js - 如何在不监听nodejs的情况下绑定(bind)TCP套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308074/