each server generated by node must be assigned a port. So if we encounter a requirement in our work: let the same port or address support both http and https protocols, HTTP and HTTPS both belong to the application layer protocol, so as long as we reverse proxy in the underlying protocol, we can solve this problem!
var fs = require("fs"); // &
var http = require("http"); // http
var path = require("path"); //
var https = require("https"); // https
var net = require("net");
var httpport = 3000;
var httpsport = 3000;
var server = http.createServer(function(req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("secured hello world");
}).listen(httpport,"0.0.0.0",function(){
console.log("HTTP Server is running on: http://localhost:%s",httpport)
});
var options = {
pfx: fs.readFileSync(path.resolve(__dirname, "config/server.pfx")),
passphrase: "bhsoft"
};
var sserver = https.createServer(options, function(req, res){
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("secured hello world");
}).listen(httpsport,"0.0.0.0",function(){
console.log("HTTPS Server is running on: https://localhost:%s",httpsport)
});
var netserver = net.createServer(function(socket){
socket.once("data", function(buf){
console.log(buf[0]);
var address = buf[0] === 22 ? httpport : httpport;
var proxy = net.createConnection(address, function() {
proxy.write(buf);
socket.pipe(proxy).pipe(socket);
});
proxy.on("error", function(err) {
console.log(err);
});
});
socket.on("error", function(err) {
console.log(err);
});
}).listen(3344);
3000
Error: listen EADDRINUSE 0.0.0.0:3000