Nodejs HTTP and HTTPS over same port

前端 未结 4 1322
逝去的感伤
逝去的感伤 2020-11-27 03:58

I\'ve been googling and looking here at stackoverflow, but I can\'t find an answer I like ;-)

I have a NodeJS server that runs over HTTPS and port 3001. Now I\'d lik

4条回答
  •  被撕碎了的回忆
    2020-11-27 04:09

    If serving HTTP and HTTPS over a single port is an absolute requirement you can proxy the request to the relevant HTTP implementation directly, rather than piping the socket to another port.

    httpx.js

    'use strict';
    let net = require('net');
    let http = require('http');
    let https = require('https');
    
    exports.createServer = (opts, handler) => {
    
        let server = net.createServer(socket => {
            socket.once('data', buffer => {
                // Pause the socket
                socket.pause();
    
                // Determine if this is an HTTP(s) request
                let byte = buffer[0];
    
                let protocol;
                if (byte === 22) {
                    protocol = 'https';
                } else if (32 < byte && byte < 127) {
                    protocol = 'http';
                }
    
                let proxy = server[protocol];
                if (proxy) {
                    // Push the buffer back onto the front of the data stream
                    socket.unshift(buffer);
    
                    // Emit the socket to the HTTP(s) server
                    proxy.emit('connection', socket);
                }
                
                // As of NodeJS 10.x the socket must be 
                // resumed asynchronously or the socket
                // connection hangs, potentially crashing
                // the process. Prior to NodeJS 10.x
                // the socket may be resumed synchronously.
                process.nextTick(() => socket.resume()); 
            });
        });
    
        server.http = http.createServer(handler);
        server.https = https.createServer(opts, handler);
        return server;
    };

    example.js

    'use strict';
    let express = require('express');
    let fs = require('fs');
    let io =  require('socket.io');
    
    let httpx = require('./httpx');
    
    let opts = {
        key: fs.readFileSync('./server.key'),
        cert: fs.readFileSync('./server.cert')
    };
    
    let app = express();
    app.use(express.static('public'));
    
    let server = httpx.createServer(opts, app);
    let ws = io(server.http);
    let wss = io(server.https);
    server.listen(8080, () => console.log('Server started'));

提交回复
热议问题