Socket.IO无法通过https连接

und*_*ned 19 javascript https websocket node.js socket.io

我有一个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);  
Run Code Online (Sandbox Code Playgroud)

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
    });
}
Run Code Online (Sandbox Code Playgroud)

客户端连接如下:

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});
Run Code Online (Sandbox Code Playgroud)

正如我所说的一切在http上工作正常,但在https上的连接给了我"连接被中断".我究竟做错了什么?

use*_*109 41

你不能socket.iohttps服务器那样初始化服务器.您必须启动一个单独的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");
Run Code Online (Sandbox Code Playgroud)

  • @AdrianSalazar是的,我使用自制文件,使用openssl命令行工具.对于生产,它将无法运行,因为证书需要由证书进行验证.权威 - 信任的网络.幸运的是,现在有办法做到这一点.联邦军最近宣布了[让我们加密](https://www.eff.org/deeplinks/2014/11/certificate-authority-encrypt-entire-web),这有助于开发人员轻松,免费地获取和维护证书.使用他们的库[node-acme](https://github.com/letsencrypt/node-acme).我不能给出详细的说明,因为这是我的知识限制,也许其他人可以. (2认同)