當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。