鍍金池/ 問答/HTML/ node怎樣讓一個端口同時支持http和https?

node怎樣讓一個端口同時支持http和https?

node生成的每個服務器必須分配一個端口。那么如果我們在工作中遇到一個需求:讓同一個端口或地址既支持http協(xié)議又支持https協(xié)議,HTTP與HTTPS都屬于應用層協(xié)議,所以只要我們在底層協(xié)議中進行反向代理,就可以解決這個問題!

    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

請問這個問題有什么辦法解決?
回答
編輯回答
下墜

你做不到,http和https協(xié)議不同,不能使用同一個端口

2018年4月6日 13:57