How to configure socket.io to run on same port on https?

Member

by mac , in category: Third Party Scripts , 3 months ago

How to configure socket.io to run on same port on https?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 3 months ago

@mac 

To configure Socket.io to run on the same port as HTTPS, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const express = require('express');
const https = require('https');
const socketio = require('socket.io');
const fs = require('fs');

const app = express();
const server = https.createServer({
  key: fs.readFileSync('path/to/private-key.pem'),
  cert: fs.readFileSync('path/to/certificate.pem')
}, app);
const io = socketio(server);

io.on('connection', (socket) => {
  console.log('A user connected');
  
  socket.on('disconnect', () => {
    console.log('A user disconnected');
  });
});

server.listen(443, () => {
  console.log('Socket.io server running on port 443');
});


In this code snippet, we create an HTTPS server using the https.createServer method, providing it with the path to the private key and certificate files. We then create a Socket.io server using the socketio module, passing the HTTPS server instance to it. Lastly, we listen on port 443 for incoming connections.


Make sure to replace path/to/private-key.pem and path/to/certificate.pem with the actual paths to your private key and certificate files, and ensure that they are valid and accessible to the server.