Socket.IO无法连接通过HTTPS(Socket.IO can't connect t

2019-07-21 18:54发布

我有一个node.js的应用程序,使用socket.IO。 它工作正常的HTTP,而是试图通过HTTPS连接到插座时, - 什么也没有发生。
下面的代码的某些部分:

var fs = require('fs');  

var ioHttp = require('socket.io').listen(8899, {  
    'flash policy port': -1  
});  

initSocket(ioHttp);  

var ioHttps = require('socket.io').listen(8895, {  
    key: fs.readFileSync('/path/to/file/file.key'),  
    cert: fs.readFileSync('/path/to/file/file.crt'),  
    ca: [  
        fs.readFileSync('/path/to/file/sub.class1.server.ca.pem'),  
        fs.readFileSync('/path/to/file/ca.pem')  
    ],  
    'flash policy port': -1   
});  

initSocket(ioHttps);  

initSocket功能:

function initSocket(io) {  
    io.enable('browser client minification');  
    io.enable('browser client etag');  
    io.enable('browser client gzip');  

    io.set('transports', [  
        'websocket',  
        'htmlfile',
        'flashsocket',
        'jsonp-polling'  
    ]);  

    io.sockets.on('connection', function (client) {
        //the connnection is handled here
    });
}

客户端连接如下:

var secureConnection = false;  
var port = 8899;
if (window.location.protocol === 'https:') {  
    port = 8895;
    secureConnection = true;
}

var socket = io.connect('domain.org', {port: port, secure: secureConnection});

正如我所说的一切正常的HTTP,但连接上的https给了我“的连接被中断”。 我究竟做错了什么?

Answer 1:

你不能initalize socket.io像服务器https服务器。 你必须启动一个单独的HTTPS服务器,然后服务器socket.io重视它。

var https = require('https'),     
    fs =    require('fs');        

var options = {
    key:    fs.readFileSync('ssl/server.key'),
    cert:   fs.readFileSync('ssl/server.crt'),
    ca:     fs.readFileSync('ssl/ca.crt')
};
var app = https.createServer(options);
io = require('socket.io').listen(app);     //socket.io server listens to https connections
app.listen(8895, "0.0.0.0");


文章来源: Socket.IO can't connect through https