Force close all connections in a node.js http server

后端 未结 5 1458
被撕碎了的回忆
被撕碎了的回忆 2020-12-28 13:33

I have an http server created using:

var server = http.createServer()

I want to shut down the server. Presumably I\'d do this by calling:

<
5条回答
  •  一生所求
    2020-12-28 13:51

    I usually use something similar to this:

    var express = require('express');
    var server = express();
    
    /* a dummy route */
    server.get('/', function (req, res) {
        res.send('Hello World!');
    });
    
    /* handle SIGTERM and SIGINT (ctrl-c) nicely */
    process.once('SIGTERM', end);
    process.once('SIGINT', end);
    
    
    var listener = server.listen(8000, function(err) {
        if (err) throw err;
    
        var host = listener.address().address;
        var port = listener.address().port;
    
        console.log('Server listening at http://%s:%s', host, port);
    });
    
    
    var lastSocketKey = 0;
    var socketMap = {};
    listener.on('connection', function(socket) {
        /* generate a new, unique socket-key */
        var socketKey = ++lastSocketKey;
        /* add socket when it is connected */
        socketMap[socketKey] = socket;
        socket.on('close', function() {
            /* remove socket when it is closed */
            delete socketMap[socketKey];
        });
    });
    
    function end() {
        /* loop through all sockets and destroy them */
        Object.keys(socketMap).forEach(function(socketKey){
            socketMap[socketKey].destroy();
        });
    
        /* after all the sockets are destroyed, we may close the server! */
        listener.close(function(err){
            if(err) throw err();
    
            console.log('Server stopped');
            /* exit gracefully */
            process.exit(0);
        });
    }
    

    it's like Ege Özcan says, simply collect the sockets on the connection event, and when closing the server, destroy them.

提交回复
热议问题