socket.io服务器 - 暂停监听和恢复

时间:2014-03-19 05:35:23

标签: javascript node.js socket.io

我需要一种机制来启动和停止socket.io服务器。当stop命令到来时,所有客户端断开连接并且服务器停止附加新连接。当启动函数调用时,套接字服务器以正常模式附加新客户端连接。

我正在尝试此代码:

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)

1 个答案:

答案 0 :(得分:0)

如果需要,我公开解决方案:

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;
})();