Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to bind a TCP socket without listening in nodejs?

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?

like image 674
HRJ Avatar asked Dec 01 '25 20:12

HRJ


1 Answers

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.

like image 166
robertklep Avatar answered Dec 04 '25 14:12

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!