如何在不监听nodejs的情况下绑定TCP套接字?

时间:2021-01-08 07:38:06

I want to reserve a port for the duration of the application, but the application shouldn't be listening on the port all the time. Hence I want to decouple the bind() call from the listen() call.

我想在应用程序期间保留一个端口,但是应用程序不应该一直监听该端口。因此,我想将bind()调用与listen()调用解耦。

The UDP/Datagram socket in nodejs has a bind function. But I couldn't find an equivalent for it in the "normal" (TCP) socket API.

nodejs中的UDP/Datagram套接字具有绑定功能。但是我在“普通”(TCP)套接字API中找不到与之对应的接口。

Is it possible to bind without listening?

是否有可能在不听的情况下约束?

1 个解决方案

#1


3  

You can create unwrapped TCP sockets:

您可以创建未封装的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);

EDIT: to instantiate a socket on Node v9.3.0 and higher, you need to pass an extra argument to the constructor:

编辑:要在Node v9.3.0或更高版本上实例化套接字,需要向构造函数传递一个额外的参数:

const TCPWrap = process.binding('tcp_wrap');
const { TCP } = TCPWrap;
const socket  = new TCP(TCPWrap.constants.SERVER); // or .SOCKET

The difference is the ability to distinguish between the two types of socket when using async_hooks.

不同之处在于使用async_hooks时能够区分两种类型的套接字。

#1


3  

You can create unwrapped TCP sockets:

您可以创建未封装的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);

EDIT: to instantiate a socket on Node v9.3.0 and higher, you need to pass an extra argument to the constructor:

编辑:要在Node v9.3.0或更高版本上实例化套接字,需要向构造函数传递一个额外的参数:

const TCPWrap = process.binding('tcp_wrap');
const { TCP } = TCPWrap;
const socket  = new TCP(TCPWrap.constants.SERVER); // or .SOCKET

The difference is the ability to distinguish between the two types of socket when using async_hooks.

不同之处在于使用async_hooks时能够区分两种类型的套接字。