node.js Socket.IO 无法通过 https 连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15449234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Socket.IO can't connect through https
提问by undefined
I have a node.js app, that uses socket.IO. It works fine on http, but when trying to connect to the socket through https - nothing happens.
Here's some part of the code:
我有一个 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);
and the initSocketfunction:
和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
});
}
The client connect like this:
客户端连接如下:
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});
As I said everything works fine on http, but connecting on https gives me "The connection was interrupted". What am I doing wrong?
正如我所说的,在 http 上一切正常,但在 https 上连接给我“连接被中断”。我究竟做错了什么?
回答by user568109
You cannot initalize socket.ioserver like httpsserver. You have to start a separate https server and then attach socket.io server to it.
您不能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");

