简体   繁体   中英

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.

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() {

});

Use letsencrypt with Plesk for a valid SSL certificat.

options = {
    key: fs.readFileSync('/usr/local/psa/var/modules/letsencrypt/etc/live/mydomain.com/privkey.pem'),
    cert: fs.readFileSync('/usr/local/psa/var/modules/letsencrypt/etc/live/mydomain.com/cert.pem'),
    ca: fs.readFileSync('/usr/local/psa/var/modules/letsencrypt/etc/live/mydomain.com/chain.pem'),
    rejectUnauthorized: false,
    requestCert: true,
    agent: false
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM