2014-03-26 90 views
2

我嘗試使用HTTP服務器調試,並socket.io工作,但是當我嘗試使用https socket.io不輟Nodejs - Socketio不能與https服務器一起工作,可能是什麼原因?

// create server for http and https 
//var httpserver = http.createServer(app).listen('3000', '127.0.0.1'); 
var https_server = https.createServer(options, app).listen('4000', '127.0.0.1'); 
// let the backend listens to this server 
UserServer.listen(https_server); 
//UserServer.listen(httpserver); 


exports.listen = function(server){ 

    io = socketio.listen(server); 
    io.sockets.on('connection', function(socket){ 
     console.log("Socket is connected, sweet "); 
    }); 
} 

var httpserver = http.createServer(app).listen('3000', '127.0.0.1'); 
UserServer.listen(httpserver); 

打印出來

Socket is connected, sweet " 

var https_server = https.createServer(options, app).listen('4000', '127.0.0.1'); 
UserServer.listen(https_server); 

有沒有輸出

這裏是我設置了HTTPS

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



var options = { 
    key: fs.readFileSync('./key.pem', 'utf8'), 
    cert: fs.readFileSync('./cert.pem', 'utf8') 
}; 

我能夠顯示HTTPS頁面,所以我猜測HTTPS安裝沒有問題

任何意見將謝謝

回答

1

首先,你需要運行Node.js Server with SSL

Server.js

var fs = require('fs');  
var options = { 
    key: fs.readFileSync('ssl/private/domain.com.key'), 
    cert: fs.readFileSync('ssl/certs/domain.com.crt'), 
    ca: fs.readFileSync('ssl/certs/domain.com.cabundle') 
}; 
// You can do this easily if you are on windows 
// var options = { pfx: fs.readFileSync('/home/mydir/secure.pfx'); }; 
var app = require('https').createServer(options, handler), 
    io = require('socket.io').listen(app);  

//Recommended Production settings 
io.enable('browser client minification'); // send minified client 
io.enable('browser client etag');   // apply etag caching logic based on version number 
io.enable('browser client gzip');   // gzip the file 
io.set('log level', 1);     // reduce logging 
io.set('flash policy port', 3300); //==> override Flash Policy Port 
io.set('transports', [      // enable all transports (optional if you want flashsocket) 
    'websocket' 
    , 'flashsocket' 
    , 'htmlfile' 
    , 'xhr-polling' 
    , 'jsonp-polling' 
]); 
function handler(req, res) { 
    res.writeHead(200); 
    res.end("welcome sir!"); 
};  
io.sockets.on('connection', function (socket) { 
    socket.on('message', function (data) { 
     socket.broadcast.emit('message', data); 
    }); 
});  
app.listen(3300); 

Client.js

//socketAddress is server uri ex. https://www.domain.com:3300 
    var socket = io.connect(socketAddress, {'flash policy port':3300}); 
    socket.on('connect', function (data) { 
     //.... 
    }); 
    socket.on('message', function (data) { 
     //.... 
    }); 
+1

謝謝,我明白,只是您配置io.set所有的代碼,你會更多地討論那部分? – xbd

+0

它與'https'沒有直接關係,它只是'推薦的生產設置'以獲得更多信息,你可以通過這個[link](https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO ) –

+1

謝謝,鏈接是相當豐富的 – xbd

相關問題