Search code examples
node.jshandle

Use net.server to handle http and express all at once


i have a server using net.Server and also have 2 servers using http.Server and express(). and it looks like this

...
var s_net = net.createServer();
var s_http = http.createServer();
var s_exp = express();
s_net.listen(opt.port);
s_http.listen(s_net);
s_exp.listen(s_net);
console.log(`listening on ${opt.port}`);

I use s_net as a handler for s_http and s_exp. and then, i do

s_net.on("connection", function(c){
    console.log("incoming connection to s_net")
})
s_http.on("request", function(req, res){
    console.log("request to s_http");
});
s_exp.all("/*", function(req, res, next){
    console.log("request to s_exp");
    res.send("<h1>Hello World!</h1>");
});

but on console, i just get

H:\NodeJS\web3>node index.js
listening on 80
request to s_exp

where does, it only respond from s_exp request.
How can I got them all?
incoming connection to s_net, request to s_http, and request to s_exp
references :
https://nodejs.org/dist/latest-v9.x/docs/api/net.html#net_server_listen_handle_backlog_callback


Solution

  • When you create a server using Express, you already have an http server. It's just an http server that has Express as a request handler for incoming requests. And, an http server inherits from net.Server so it's already a TCP/IP server. Create the one express server and then you can use any express, http or net.Server features on it including setting event listeners for various server events.

    So, just creating a generic Express server already has all three together. There is no need or point to creating three separate servers and then trying to combine them somehow.