Last active
February 3, 2019 19:03
-
-
Save adamelliotfields/4deeaa04eec5320f7d3fece9e335cada to your computer and use it in GitHub Desktop.
Node HTTP Server Destroy Sockets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* Destroy all open connections so a server can close. | |
* Inspired by https://github.com/marten-de-vries/killable | |
*/ | |
import http from 'http'; | |
import { Socket } from 'net'; | |
// Set of open sockets | |
const sockets: Set<Socket> = new Set(); | |
const signals: Array<NodeJS.Signals> = ['SIGINT', 'SIGTERM', 'SIGUSR2']; | |
const server = http.createServer((req, res) => { | |
res.writeHead(200, { 'Content-Type': 'text/plain' }); | |
// Don't end the response to keep the connection open | |
// res.end('OK'); | |
}); | |
server.on('connection', (socket) => { | |
// Add the new socket to the set | |
sockets.add(socket); | |
// Once the socket closes it can be removed from the set | |
socket.once('close', () => { | |
sockets.delete(socket); | |
}); | |
}); | |
server.on('listening', () => { | |
console.log('Listening'); | |
}); | |
// Emitted once all sockets have been closed | |
server.on('close', () => { | |
process.exit(0); | |
}); | |
server.listen(8080); | |
signals.forEach((signal) => { | |
process.on(signal, () => { | |
console.log('Closing'); | |
// Stop accepting incoming connections | |
server.close(); | |
// Destroy each socket | |
sockets.forEach((socket) => { | |
socket.destroy(); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment