0

I have a Node.JS server with Socket.IO that runs over HTTPs with Express. With this all users connect through an address, e.g. https://socket.example.com:443,

The problem is that virtual machines on the same local network have to take a longer path to the Socket.IO server, even though they are on the same network.

Is it possible to run the same NodeJS+Socket.IO application both with HTTPs and HTTP?

In this way, applications on the same network could connect to the server with just http + the machine's IP (eg.: http:192.168.0.1:3400), gaining more communication speed (and lowering costs on Google Cloud).

I run the application this way.

app = require('express')(),
serverSSL = require('https').Server(credentials, app);

io = require('socket.io')(serverSSL, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

Or will I have to put an nginx proxy to connect to the server via HTTPs and keep it running with HTTP on the main server?

-- EDIT 2022-01-18 --

My plan is to use PM2 to run the code, and since socket.IO requires an HTTP or HTTPS server at startup, I think it's better to use an HTTP server and a load balancer with NGINX to handle HTTPS.

https://socket.io/docs/v4/pm2/

-- EDIT 2022-01-19 --

Solution: https://github.com/socketio/socket.io/discussions/4600

Tom
  • 641
  • 2
  • 8
  • 21
  • Does this answer your question? [Enabling HTTPS on express.js](https://stackoverflow.com/questions/11744975/enabling-https-on-express-js) – gre_gor Jan 18 '23 at 20:54

1 Answers1

1
  • The thing is you cannot run http and https from the same port in nodejs But instead you can create two different servers like this


    const http = require('http');
    const https = require('https');
    const { Server } = require('socket.io');
    
    //httpServer
    const httpServer = http.createServer((req, res) => {
      res.writeHead(200);
      res.end('http server');
    });
    
    //httpserver
    const httpsServer = https.createServer({
      key: fs.readFileSync('path/to/key.pem'),
      cert: fs.readFileSync('path/to/cert.pem')
    }, (req, res) => {
      res.writeHead(200);
      res.end('https server');
    });

    //Initializing our socket.io Server
    const io = new Server({
      cors: {
        "Access-Control-Allow-Origin": "*",
        methods: ["GET", "POST", "OPTIONS"]
      },
      maxHttpBufferSize:1e8,
      pingTimeout:60000
    });

    
    io.attach(httpServer)
    io.attach(httpsServer)
    httpServer.listen(3000)
    httpServer.listen(4000)

  • .attach() works properly in older versions, however it is recommended to use .listen()
  • In place of the traditional http and https server, express http and https server can easily be used
  • The attached http and https server will listen to the same events
  • Therefore the clients you want can use both http and https servers