Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js, socket.io https connection

Server side code:

var io = require('socket.io').listen(8150);
io.sockets.on('connection', function (socket){

});

Client side code:

var socketIO = io('*.*.*.*:8150');
socketIO.once('connect', function(){

});

On http it's worked on https in same page it not connected. Searched many examples, but all example for express. I dont create any http server in node.js need only to socket.io work.

like image 594
PainMustDie Avatar asked Mar 08 '23 11:03

PainMustDie


1 Answers

When running the client over HTTPS, socket.io is attempting to connect to your server over HTTPS as well. Currently your server is only accepting HTTP connections, the listen(port) function does not support HTTPS.

You'll need to create an HTTPS server and then attach socket.io to it, something like this.

var fs = require('fs');

var options = {
  key: fs.readFileSync('certs/privkey.pem'),
  cert: fs.readFileSync('certs/fullchain.pem')
};

var app = require('https').createServer(options);
var io = require('socket.io').listen(app);
app.listen(8150);

io.sockets.on('connection', function (socket) {

});

And if you need both HTTP and HTTPS, you can start two servers and attach socket.io to both.

var fs = require('fs');

var options = {
  key: fs.readFileSync('certs/privkey.pem'),
  cert: fs.readFileSync('certs/fullchain.pem')
};

var httpServer = require('http').createServer();
var httpsServer = require('https').createServer(options);
var ioServer = require('socket.io');

var io = new ioServer();
io.attach(httpServer);
io.attach(httpsServer);
httpServer.listen(8150);
httpsServer.listen(8151);

io.sockets.on('connection', function (socket) {

});

Then on the client side you can determine which port to connect to based on whether the page was accessed over HTTP or HTTPS.

var port = location.protocol === 'https:' ? 8151 : 8150;
var socketIO = io('*.*.*.*:' + port);
socketIO.once('connect', function() {

});
like image 93
Eric B Avatar answered Mar 20 '23 08:03

Eric B