response.socket


引用底层套接字。通常用户不需要访问此属性。特别地,由于协议解析器附加到套接字的方式,套接字不会触发 'readable' 事件。在 response.end() 之后,该属性将被置为 null。

【Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit 'readable' events because of how the protocol parser attaches to the socket. After response.end(), the property is nulled.】

import http from 'node:http';
const server = http.createServer((req, res) => {
  const ip = res.socket.remoteAddress;
  const port = res.socket.remotePort;
  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);const http = require('node:http');
const server = http.createServer((req, res) => {
  const ip = res.socket.remoteAddress;
  const port = res.socket.remotePort;
  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);

此属性保证是 <net.Socket> 类的一个实例,<stream.Duplex> 的子类,除非用户指定了 <net.Socket> 以外的套接字类型。

【This property is guaranteed to be an instance of the <net.Socket> class, a subclass of <stream.Duplex>, unless the user specified a socket type other than <net.Socket>.】