Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

javascript - Socket.IO can't connect through 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);  

and the initSocket function:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...