Socket.IO 无法通过 https 连接 [英] Socket.IO can't connect through https

查看:116
本文介绍了Socket.IO 无法通过 https 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 socket.IO 的 node.js 应用程序.它在 http 上运行良好,但是当尝试通过 https 连接到套接字时 - 没有任何反应.
这是代码的一部分:

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:

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 上连接却给我连接被中断".我做错了什么?

As I said everything works fine on http, but connecting on https gives me "The connection was interrupted". What am I doing wrong?

推荐答案

你不能像 https 服务器那样初始化 socket.io 服务器.您必须启动一个单独的 https 服务器,然后将 socket.io 服务器连接到它.

You cannot initalize socket.io server like https server. You have to start a separate https server and then attach socket.io server to it.

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 无法通过 https 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆