简体   繁体   English

访问套接字引用以传递给子进程

[英]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:使用 Node.js,我可以使用此构造将 http 请求的句柄/引用传递给子进程:

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:我想知道如何为 websocket 服务器做同样的事情:

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?不确定 websocket 连接是否有 sockets 和 http 连接一样?

This handle type cannot be sent无法发送此句柄类型

websocket connections are just a TCP connection underneath their protocol parsing layer. websocket 连接只是其协议解析层下的 TCP 连接。 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.事实上,它们从 http 连接开始,然后通过将 webSocket 协议层传递到 webSocket 协议层,将 http 连接的 TCP 套接字转换为 webSocket 协议。

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.无法将 webSocket 传递给子进程并不是因为您无法传递 TCP 套接字,而是因为没有人编写代码来围绕传递的 TCP 套接字在子进程中连接新的 webSocket 包装器. 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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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