2014-03-19 76 views
0

我需要一種機制來啓動和停止socket.io服務器。當停止命令到來時,所有客戶端斷開連接並且服務器停止附加新連接。當啓動函數調用時,套接字服務器以正常模式追加新的客戶端連接。socket.io服務器 - 暫停監聽和恢復

我想這樣的代碼:

var app = require('http').createServer(function() {}), 
io = require('socket.io').listen(app); 

app.listen(25544); 

io.set('log level', 1); 
io.set('close timeout', 240); 
io.set('heartbeat timeout', 240); 
io.set('heartbeat interval', 120); 

io.startServer = function() { 
    app.listen(25544); 
}; 

io.stopServer = function() { 
    app.close() 
}; 

但是,當我打電話app.close(),我正在錯誤:

net.js:1236 
    throw new Error('Not running'); 
     ^
Error: Not running 
    at Server.close (net.js:1236:11) 
    at Manager.module.exports.io.stopServer (/home/streamuser/nodejs/data/io.js:22:10) 
    at process.<anonymous> (/home/streamuser/nodejs/data/app.js:146:7) 
    at process.EventEmitter.emit (events.js:98:17) 
    at handleMessage (child_process.js:318:10) 
    at Pipe.channel.onread (child_process.js:345:11) 
+0

請執行以下操作:app.listen(25544,function(){console.log(「server running」)});並檢查控制檯是否輸出'服務器運行'或不。 –

回答

0

如果有任何需要1,我公解決方案:

module.exports = (function() { 
    var https = require("https"), 
    fs = require("fs"), 
    app = https.createServer({ 
     key: fs.readFileSync(BASE_DIR + '/private.pem').toString(), 
     cert: fs.readFileSync(BASE_DIR + '/public.pem').toString() 
    }), 
    io = require("socket.io").listen(app); 

    io.listeningClients = false; 

    var oldListeners = app.listeners('request').splice(0); 
    app.removeAllListeners('request'); 

    app.on('request', function (req, res) { 
     if (! (io.listeningClients || req.url.indexOf('.js') !== -1)) { 
      res.writeHead(404, {"Content-Type": "text/plain"}); 
      res.write('Socket.io stop listening. Try again later.'); 
      res.end(); 
      return; 
     } 

     for (var i = oldListeners.length; i--;) { 
      oldListeners[i].call(app, req, res); 
     } 
    }); 

    io.set('log level', 1); 
    io.set('reconnect', false); 
    io.set('reconnection limit', 20000); 
    io.set('max reconnection attempts', Infinity); 
    io.set('close timeout', 240); 
    io.set('heartbeat timeout', 240); 
    io.set('heartbeat interval', 120); 


    io.startListeningClients = function() { 
     if (io.listeningClients) { 
      return; 
     } 

     io.listeningClients = true; 
     app.listen(25544, function() {}); 
    }; 

    io.stopListeningClients = function() { 
     if (! io.listeningClients) { 
      return; 
     } 

     io.listeningClients = false; 
     app.close(); 

     var clients = io.sockets.clients(); 
     for (var i in clients) { 
      clients[i].disconnect(); 
     } 
    }; 

    return io; 
})();