简体   繁体   中英

Access socket ref to pass to child process

Using Node.js, I can pass a handle/ref for a http request to a child process using this construct:

const k = cp.fork(childPath);

const server = http.createServer((req,res) => {
  k.send('foo', req.socket);
});

and in the child process, I can do:

process.on('message', (m, socket) => {
    // 'foo', socket
    socket.write([
      'HTTP/1.1 200 OK',
      'Content-Type: text/html; charset=UTF-8',
      'Content-Encoding: UTF-8',
      'Accept-Ranges: bytes',
      'Connection: keep-alive',
    ].join('\n') + '\n\n');
  
    socket.write(`
    <h1> Example </h1>
  `);
    
    socket.end('foobar');
};

which is pretty cool, allows child processes to write directly to requests.

I am wondering, how I can do the same for a websocket server:

const ws = require('ws');
const server = new ws.WebSocketServer({port: 5151});

I assume passing a connection to a child process should work:

server.on('connection', c => {
   k.send('foo', c);  /// error here
});

but I get an error , saying:

This handle type cannot be sent

not sure if websocket connections have sockets as do http connections?

This handle type cannot be sent

websocket connections are just a TCP connection underneath their protocol parsing layer. In fact, they start life as an http connection and that very TCP socket of the http connection is then converted to the webSocket protocol by passing it to a webSocket protocol layer.

The lack of being able to pass a webSocket to a child process is not because you can't pass the TCP socket, it's because nobody has written the code to hook up a new webSocket wrapper in the child process around the TCP socket that gets passed. Probably just hasn't been a serious priority to write that code.

Looks like it's accessible via an underscored property:

server.on('connection', c => {

    console.log('new connection');

    const k = cp.fork('k.js', [],{
        stdio: 'pipe',
        detached: false
    });


    k.send({handle:true}, c._socket); // <--- 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