如何立即關(guān)閉 Node 服務(wù)器?

我有一個(gè)包含 http服務(wù)器的 Node.js 應(yīng)用程序,在特定情況下,我需要以編程方式關(guān)閉此服務(wù)器。
const http = require('http');const server = http.createServer((req, res) => {res.end();});server.on('clientError', (err, socket) => {socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');});server.listen(8000);
在 node 中提供了server.close([callback]) 方法,返回 server。停止 server 接受建立新的connections 并保持已經(jīng)存在的 connections。
此功能是異步的,當(dāng)所有的 connections 關(guān)閉同時(shí) server 響應(yīng) ['close'][]事件的時(shí)候,server 將會(huì)最終關(guān)閉. 一旦?'close'?發(fā)生將會(huì)調(diào)用可選的回調(diào)函數(shù)。與該事件不同, 如果服務(wù)器在關(guān)閉時(shí)未打開(kāi),則將使用錯(cuò)誤作為唯一參數(shù)。
我目前正在做的是調(diào)用它的 close() 函數(shù),但這沒(méi)有用,因?yàn)樗却魏伪3只顒?dòng)的連接首先完成。
因此,基本上,這會(huì)關(guān)閉服務(wù)器,但僅在最短120秒的等待時(shí)間之后。但我希望服務(wù)器立即關(guān)閉 - 即使這意味著與當(dāng)前處理的請(qǐng)求分手。
訣竅是你需要訂閱服務(wù)器的 connection 事件,它為你提供了新連接的套接字。你需要記住這個(gè)套接字,然后在調(diào)用之后直接 server.close() 使用它來(lái)銷毀該套接字 socket.destroy()。
此外,如果套接字的 close 事件自然離開(kāi),則需要監(jiān)聽(tīng)套接字的事件以將其從數(shù)組中刪除,因?yàn)樗谋3只顒?dòng)超時(shí)確實(shí)已用完。
我編寫了一個(gè)小示例應(yīng)用程序,您可以使用它來(lái)演示此行為:
// Create a new server on port 4000var http = require('http');var server = http.createServer(function (req, res) {res.end('Hello world!');}).listen(4000);// Maintain a hash of all connected socketsvar sockets = {}, nextSocketId = 0;server.on('connection', function (socket) {// Add a newly connected socketvar socketId = nextSocketId++;sockets[socketId] = socket;console.log('socket', socketId, 'opened');// Remove the socket when it closessocket.on('close', function () {console.log('socket', socketId, 'closed');delete sockets[socketId];});// Extend socket lifetime for demo purposessocket.setTimeout(4000);});// Count down from 10 seconds(function countDown (counter) {console.log(counter);if (counter > 0)return setTimeout(countDown, 1000, counter - 1);// Close the serverserver.close(function () { console.log('Server closed!'); });// Destroy all open socketsfor (var socketId in sockets) {console.log('socket', socketId, 'destroyed');sockets[socketId].destroy();}})(10);
