📜  Node.js request.socket 属性

📅  最后修改于: 2022-05-13 01:56:30.543000             🧑  作者: Mango

Node.js request.socket 属性

request.socket在 v0.3.0 中添加)属性是“ http ”模块的内置属性,它 对底层套接字的引用,大多数用户无法访问此属性。特别是,套接字不会发出“可读”事件,但可以通过request.connection访问套接字。此属性保证是 < net.Socket > 类的实例, 的子类。

为了得到响应和正确的结果,我们需要导入' http '模块。

const http = require('http'); 

句法:

request.socket

参数:此属性不接受任何参数。

返回值:以对象的形式返回请求数据,其中包含大量与socket相关的数据。

  • < stream.Duplex >:< stream.Duplex >或者说双工流是实现了可读和可写的流。

以下示例说明了 Node.js 中request.socket属性的使用。

示例 1:文件名:index.js

// Node.js program to demonstrate the 
// req.socket property 
  
// Using require to access http module 
const http = require('http');
  
// Requesting from google server
const req = http.get({ host: 'www.geeksforgeeks.org' });
  
// Ending the request
req.end();
  
req.once('response', (res) => {
  
    // Printing socket after getting response
    console.log(req.socket);
  
    // Printing address and port after
    // getting response
    console.log(`IP address of geeksforgeeks is 
            ${req.socket.localAddress}.`);
              
    console.log(`Its Port is ${req.socket.localPort}.`);
});

输出:

示例 2:文件名:index.js

// Node.js program to demonstrate the 
// req.socket property 
  
// Using require to access http module 
const { get } = require('http');
  
// Setting host server url
const options = { host: 'www.geeksforgeeks.org' };
  
// Requesting from geeksforgeeks server
const req = get(options);
req.end();
  
req.once('response', (res) => {
  
    // Printing the requestrelated data
    console.log("Status:", res.statusCode, 
                        res.statusMessage);
  
    console.log("Host:", req.socket._host);
  
    console.log("Method:", 
        req.socket.parser.outgoing.method);
  
    console.log("Parser Header:", 
            req.socket.parser.outgoing._header);
  
    console.log("Writable:", req.socket.writable);
    console.log("Readable:", req.socket.readable);
      
    console.log("Http Header:", 
            req.socket._httpMessage._header);
  
    if (req.socket._httpMessage._header === 
            req.socket.parser.outgoing._header) {
        console.log("Both headers are exactly same...")
    } else {
        console.log("Headers are not same...")
    }
  
    // Printing address and port after
    // getting response
    console.log(`IP address of geeksforgeeks is 
        ${req.socket.localAddress}.`);
  
    console.log(`Its port is ${req.socket.localPort}.`);
});

使用以下命令运行index.js文件:

node index.js

输出:

参考: https://nodejs.org/api/http.html#http_request_socket