为什么在我只调用 socket.emit('timeout') 时会触发 res & socket 'timeout' 处理程序?

Why both res & socket 'timeout' handler are triggered while I only call socket.emit('timeout')?

为什么会同时触发 res 和 socket 'timeout' 处理程序 而我只打电话

socket.emit('timeout');

不确定这对您来说是否显而易见。谢谢。

[输出]

[Function]
[Function]
true
timeout
timeout2

[代码]

var http = require('http');

function http_relay(req, res){
    //console.log(res);
    console.log(req.socket === res.socket);
    //console.log(res.
    console.log(res.socket._events.timeout)
    console.log(res.connection._events.timeout)
    console.log(res.socket._events.timeout === res.connection._events.timeout)

    res.on('timeout',function(){
        //res.end();
        console.log('timeout');
    });

socket = res.socket;
    socket.on('timeout',function(){
        //res.end();
        console.log('timeout2');
    });

socket.emit('timeout');
//res.emit('timeout');
}


    ser = http.createServer(http_relay);

    ser.listen(8080);

当有传入的 http 连接时,http.ServerResponse class 使用以下方法为套接字超时事件挂接一个侦听器:

socket.on('timeout', ...)

当它收到该事件时,它会执行以下操作:

res.emit('timeout', ...)

一般的想法是,开发人员通常不会直接与 socket 本身交互,而只是与 response 对象交互。

因此,当您在套接字上手动触发超时事件时,响应对象的事件侦听器会看到该超时事件并在响应对象上触发超时事件。

您可以在 the nodejs Github repository 中查看代码。