Force close all connections in a node.js http server

后端 未结 5 1483
被撕碎了的回忆
被撕碎了的回忆 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:49

    My approach comes from this one and it basically does what @Ege Özcan said.

    The only addition is that I set a route to switch off my server because node wasn't getting the signals from my terminal ('SIGTERM' and 'SIGINT').

    Well, node was getting the signals from my terminal when doing node whatever.js but when delegating that task to a script (like the 'start' script in package.json --> npm start) it failed to be switched off by Ctrl+C, so this approach worked for me.

    Please note I am under Cygwin and for me killing a server before this meant to close the terminal and reopen it again.

    Also note that I am using express for the routing stuff.

    var http=require('http');
    var express= require('express');
    
    var app= express();
    
    app.get('/', function (req, res) {
        res.send('I am alive but if you want to kill me just go to /exit');
    });
    
    app.get('/exit', killserver);
    
    var server =http.createServer(app).listen(3000, function(){
      console.log('Express server listening on port 3000');
      /*console.log(process);*/
    });
    
    
    // Maintain a hash of all connected sockets
    var sockets = {}, nextSocketId = 0;
    server.on('connection', function (socket) {
      // Add a newly connected socket
      var socketId = nextSocketId++;
      sockets[socketId] = socket;
      console.log('socket', socketId, 'opened');
    
      // Remove the socket when it closes
      socket.on('close', function () {
        console.log('socket', socketId, 'closed');
        delete sockets[socketId];
      });
    
      // Extend socket lifetime for demo purposes
      socket.setTimeout(4000);
    });
    
    
    // close the server and destroy all the open sockets
    function killserver() {
        console.log("U killed me but I'll take my revenge soon!!");
      // Close the server
      server.close(function () { console.log('Server closed!'); });
      // Destroy all open sockets
      for (var socketId in sockets) {
        console.log('socket', socketId, 'destroyed');
        sockets[socketId].destroy();
      }
    };
    

提交回复
热议问题