当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js http.ClientRequest.reusedSocket用法及代码示例


http.ClientRequest.reusedSocket是HTTP模块中ClientRequest类的内置应用程序编程接口,用于检查请求是否通过重用套接字发送。

用法:

const request.reusedSocket

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

返回值:此属性返回客户端request-host的对象。

范例1:Filename-index.js



Javascript

// Node.js program to demonstrate the   
// request.reusedSocket method 
  
// Importing http module 
const http = require('http'); 
  
// Create an HTTP server 
const server = http.createServer((req, res) => { 
  res.writeHead(200, { 'Content-Type':'text/plain' }); 
  res.end('okay'); 
}); 
  
// Now that server is running 
server.listen(3000, '127.0.0.1', () => { 
  
  // Make a request 
  const options = { 
    port:3000, 
    host:'127.0.0.1', 
    headers:{ 
      'Connection':'Upgrade', 
      'Upgrade':'websocket'
    } 
  }; 
  
  // Getting client request 
  const req = http.request(options); 
  
  req.host = '127.0.0.1'
  
  // Checking if the message has been 
  // sent through reusedSocket or not 
  // by using host method 
  const v = req.reusedSocket; 
  
  // Display the result 
  if (v) 
    console.log("message is sent through reusedSocket") 
  else
    console.log("message is not sent through reusedSocket") 
  
  process.exit(0) 
});

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

node index.js

输出:

message is not sent through reusedSocket

示例2:Filename-index.js

Javascript

// Node.js program to demonstrate the   
// request.reusedSocket method 
  
// Importing http module 
const http = require('http'); 
  
// Create an HTTP server 
http.createServer((req, res) => { }) 
  .listen(3000, '127.0.0.1', () => { 
  
  // Getting client request 
  const req = http.request({ 
    port:3000, 
    host:'127.0.0.1', 
  }); 
  
  // Checking if the message has been 
  // sent through reusedSocket or not 
  // by using host method 
  if (req.reusedSocket) 
    console.log("message is sent through reusedSocket") 
  else
    console.log("message is not sent through reusedSocket") 
  
  process.exit(0) 
});

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

node index.js

输出:

message is not sent through reusedSocket

参考:https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_reusedsocket

相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Node.js http.ClientRequest.reusedSocket Property。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。