首页 文章详情

如何立即关闭 Node 服务器?

前端精髓 | 302 2022-05-29 14:52 0 0 0
UniSMS (合一短信)


我有一个包含 http服务器的 Node.js 应用程序,在特定情况下,我需要以编程方式关闭此服务器。


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 并保持已经存在的 connections。


此功能是异步的,当所有的 connections 关闭同时 server 响应 ['close'][]事件的时候,server 将会最终关闭. 一旦 'close' 发生将会调用可选的回调函数。与该事件不同, 如果服务器在关闭时未打开,则将使用错误作为唯一参数。


我目前正在做的是调用它的 close() 函数,但这没有用,因为它等待任何保持活动的连接首先完成。


因此,基本上,这会关闭服务器,但仅在最短120秒的等待时间之后。但我希望服务器立即关闭 - 即使这意味着与当前处理的请求分手。


诀窍是你需要订阅服务器的 connection 事件,它为你提供了新连接的套接字。你需要记住这个套接字,然后在调用之后直接 server.close() 使用它来销毁该套接字 socket.destroy()。


此外,如果套接字的 close 事件自然离开,则需要监听套接字的事件以将其从数组中删除,因为它的保持活动超时确实已用完。


我编写了一个小示例应用程序,您可以使用它来演示此行为:

// 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 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);});
// Count down from 10 seconds(function countDown (counter) { console.log(counter); if (counter > 0) return setTimeout(countDown, 1000, counter - 1);
// 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(); }})(10);


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter