如果有人感兴趣,我会自己找到解决方案(很想听听评论中的反馈)。
我为服务器上打开的连接添加了一个侦听器,将对这些连接的引用存储在数组中。关闭连接后,将从阵列中将其删除。
当服务器被杀死时,每个连接都通过调用其
end方法来关闭。对于某些浏览器(例如Chrome),这还不够,所以在超时后,我会调用
destroy每个连接。
const express = require('express');const app = express();app.get('/', (req, res) => res.json({ ping: true }));const server = app.listen(3000, () => console.log('Running…'));setInterval(() => server.getConnections( (err, connections) => console.log(`${connections} connections currently open`)), 1000);process.on('SIGTERM', shutDown);process.on('SIGINT', shutDown);let connections = [];server.on('connection', connection => { connections.push(connection); connection.on('close', () => connections = connections.filter(curr => curr !== connection));});function shutDown() { console.log('Received kill signal, shutting down gracefully'); server.close(() => { console.log('Closed out remaining connections'); process.exit(0); }); setTimeout(() => { console.error('Could not close connections in time, forcefully shutting down'); process.exit(1); }, 10000); connections.forEach(curr => curr.end()); setTimeout(() => connections.forEach(curr => curr.destroy()), 5000);}


