Nodejs - Socketio无法使用https服务器,可能是什么原因?

时间:2014-03-26 02:23:43

标签: node.js sockets https socket.io

我尝试使用http服务器调试,而socket.io工作,但是当我尝试使用https socket.io停止工作时

// 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 个答案:

答案 0 :(得分: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) {
      //.... 
   });