简体   繁体   中英

NodeJS How to implement request/response in net module

I am new to NodeJS and working on a project in which I am using 'net' module. My question is can we implement request, response model using 'net' module as we can achieve in HTTP module ie I want that when user type localhost:port number in browser I can send response to the browser. I can achieve the same using HTTP and unable to understand the basic difference between 'Net' and 'HTTP' module:

My 'Net' Module code is :

var net = require('net');
var server = net.createServer(function (con)
{   
    con.on('data', function (data)
    {
        <some code>
    });

    con.on('end', function ()
    {
        console.log('nodeServer disconnected');
    });
});
server.listen(8888, function ()
{ 
  console.log('nodeServer listening port:8888');
});

Following is the 'HTTP' module code:

var http = require("http");
var fs = require("fs");
http.createServer(function(req, res){
    res.writeHead(200, { 'Content-Type': 'application/json', "Access-Control-Allow-Origin":"*" });
    var obj = JSON.parse(fs.readFileSync('test', 'utf8'));
    res.write(JSON.stringify(obj, null, 4));
    res.end();  
}).listen(8888);

The reason I want to implement to implement this in Net module is that I am getting some XML from a url after fixed interval which I need to convert to JSON and return the JSON to user when requested.

You can have a look at this post nodejs - net or http module

It states that http is built on top of net

I can't see this on the NodeJS doc pages though

http://nodejs.org/api/net.html

http://nodejs.org/api/http.html

Basically you use the net module when you need to do lower level things than what http module let you do.

http : wraps everything in the request and response objects for you to interact with.

net : gives you the TCP socket itself for you to do whatever you want.

@neil-shah indeed http is based on net as you can see here: https://github.com/nodejs/node/blob/master/lib/_http_server.js#L4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM