Home > OS >  How to pass WS connection socket from parent process to child process
How to pass WS connection socket from parent process to child process

Time:12-30

There is an example here: https://github.com/websockets/ws/issues/154

In the parent we have:

const cp = require('child_process');
const http = require('http');

const child = cp.fork('child.js');
const server = http.createServer();

server.on('upgrade', (request, socket) => {
  child.send({ headers: request.headers, method: request.method }, socket);
});

server.listen(8080);

and in the child process we have:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ noServer: true });

process.on('message', (request, socket) => {
  wss.handleUpgrade(request, socket, undefined, (ws) => {
    ws.send('foo');
  });
});

my question: for my use-case, I would like the websocket server in the parent process, but allow the child process to write directly to the sockets of the WSS connections, is this possible?

CodePudding user response:

The Node.js cluster module allows you to listen in the server process but have a worker (child) process handle the communication.

In cluster mode you call createServer() in the worker process but Node.js will actually create the listen socket in the master process. When a client connects, the socket will be transferred to a worker process to further handle the communication. Node.js uses a round-robin approach to select the next worker.

In the master process you can create new worker processes using cluster.fork(). This eventually calls child_process.fork().

Often you create a fixed number of worker processes, for example a worker process per CPU core. But you can create and destroy worker processes as you see fit.

CodePudding user response:

Hope this will help you.

When you call server.listen(...) in a worker, it serializes the arguments and passes the request to the master process. If the master process already has a listening server matching the worker's requirements, then it passes the handle to the worker. If it does not already have a listening server matching that requirement, then it will create one, and pass the handle to the child.

check here

  • Related