Node request property 'socket'
Overview
In this shot, we will learn about the request property socket. Socket is the term that is used when a connection is created and communication between more than one computer is made possible.
The request.socket property returns all the details, like localAddress, socket.writable, socket.readable of the socket connection in the JSON object.
Code
Let’s use the request.socket property to get all the details of the socket that we created:
const http = require('http')const port = 8080const server = http.createServer((req,res)=>{res.statusCode = 400;res.end();});const listener= server.listen(port, () => {console.log(`Server running at port ${port}`)var request = http.request({port: 8080,host: '127.0.0.1',});request.end();request.once('response', (res) => {console.log(request.socket);})})setTimeout(()=>{server.close()},5000)
Code explanation
In the code given above:
-
In line 1, we import the HTTP module.
-
In line 3, we define the port number of the server.
-
In line 5, we use
http.createServer()to create a server. -
In line 6, just for learning purposes, we define
res.statusCodeto 400, which is returned when the request is made. -
In line 10, we start the server, using
server.listen(). When the server is running, we make the request to the server itself in the callback function. -
In line 13, we make a http request, using
http.request(). This is a get request by default, with parameters defined in the object. -
In line 18,
request.end()is important as it finishes the request. If we don’t useend(), the request will be made but the server will wait for the incoming data untilend()is called. -
In line 20, we listen to the response event on the request that we made. In this event, we print the
socketdetails of the connection by using therequest.socketproperty, which returns all the details of the socket. -
In line 26, we use
setTimeout() because the educative feature of a running server does not stop until we call theserver.close()function. It will still gives us the desired result, but with anexecution timeout` error. We don’t need to write this on our personal machine.
Output
When we listen to the response event and print the socket details on the console, it is an object with lots of socket details.