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.
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.
Is it possible to bind without listening?
You can create unwrapped TCP sockets:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With