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


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


http.ClientRequest.socket是http模块内的ClientRequest类的内置应用程序编程接口,用于获取充当net.Socket的Proxy对象。

用法:

request.socket

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

返回值:此属性返回充当net.Socket的Proxy对象。

示例1:Filename:index.js



Javascript

// Node.js program to demonstrate the   
// request.socket property 
    
// Importing http module  
var http = require('http');  
    
// Setting up PORT  
const PORT = process.env.PORT || 3000;  
    
// Creating http Server  
var httpServer = http.createServer( 
  function(request, response) {  
  
  // Getting proxy socket  
  // by using request.socket 
  const value = request.socket; 
    
  // Display result 
  response.end( value.remoteFamily, 'utf8', () => {  
    console.log("Writing remotefamily of socket...");  
  
    httpServer.close(() => { 
      console.log("server is closed") 
    }) 
  });  
});  
    
// Listening to http Server  
httpServer.listen(PORT, () => {  
    console.log("Server is running at port 3000...");  
});

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

node index.js

输出:

Server is running at port 3000...

现在打开浏览器并转到http://localhost:3000 /,您将在屏幕上看到以下输出:

IPv6

现在关闭浏览器,您将在终端屏幕上看到以下输出:

Server is running at port 3000...
Writing remotefamily of socket...
server is closed

示例2:Filename:index.js

Javascript

// Node.js program to demonstrate the   
// request.socket property 
    
// Importing http module  
var http = require('http');  
  
// Request and response handler  
const http2Handlers = (request, response) => {  
    
  // Getting proxy socket  
  // by using request.socket method 
  const value = request.socket; 
    
  // Display result 
  response.end( value.remoteFamily, 'utf8', () => {  
    console.log("Writing remotefamily of socket...");  
  
    httpServer.close(() => { 
        console.log("server is closed") 
    }) 
  }); 
};  
    
// Creating http Server  
var httpServer = http.createServer 
  (http2Handlers).listen(3000, () => {  
    console.log("Server is running at port 3000...");  
});

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

node index.js

输出:

Server is running at port 3000...

现在打开浏览器并转到http://localhost:3000 /,您将在屏幕上看到以下输出:

IPv6

现在关闭浏览器,您将在终端屏幕上看到以下输出:

Server is running at port 3000...
Writing remotefamily of socket...
server is closed

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

相关用法


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