简体   繁体   中英

Socket.io works fine over HTTP but fails to make a connection over HTTPS

So, i've just updated my site to use HTTPS, and when i did that all my sockets broke.

I updated socket = io.connect( ' http://xxxx:8081 ' );

to socket = io.connect( ' https://xxxx:8081 ', {secure: true} );

but that doesn't do it.

I'm using apache and the SSL cert is LetsEncrypt, so not self signed.

It looks as though as if the socket.io is still trying to connect over HTTP, while it forces HTTPS.

I know this is not much information to go on. Please let me know if i can add any more logs that would make the issue more clear.

My NodeServer.js:

var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );

var app = express();
var server = http.createServer( app );

var io = socket.listen( server);
io.set('transports',['xhr-polling']);
io.sockets.on( 'connection', function( client ) {
        console.log( "New client !" );

        client.on( 'message', function( data ) {
                console.log( 'Message received ' + data.name + ":" + data.message );
                //client.broadcast.emit( 'message', { name: data.name, message: data.message } );
                io.sockets.emit( 'message', data);
        });

        client.on( 'doTrade', function( data ) {
                //console.log( 'Message received ' + data.name + ":" + data.message );
                io.sockets.emit( 'doTrade', data );
        });
});

server.listen( 8081 );

Previously your server was running on http and now as you want to connect to your server with https .

You'll to create an https server.

This is how you do that

var express = require('express'),
app = express(),
https = require('https');
var privateKey  = fs.readFileSync('pathToYourKeyFile/[KeyFile.key]', 'utf8');
var certificate = fs.readFileSync('PathToCertFile/[Crt.crt]', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(8081);

Now you should successfully be able to connect with this server with socket

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