简体   繁体   中英

How to pass WS connection socket from parent process to child process

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?

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.

While it is at least on UNIX systems possible to send a plain TCP socket using IPC to another process, this is not possible for TLS connections as needed for WSS. This is because the TLS state is inside the user space of the process which has done the TLS handshake. This state cannot be simply serialized and transferred to another process since it is intertwined with various structures in the SSL library using pointers into the memory of the parent process.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM