IT Log

Record various IT issues and difficulties.

The built-in Python http.server module cannot close the socket by itself


To address the issue where Python’s http.server module doesn’t close sockets automatically, we’ll create a custom HTTPServer subclass that ensures all sockets are closed upon shutdown. Here’s how to implement it:

Solution Code

Explanation

  1. CustomHTTPServer Class:
  2. Inherits from http.server.HTTPServer.
  3. Maintains a list of sockets ( _base_sockets) to track all open connections.
  4. Overrides the shutdown() method to close all sockets before calling the parent’s shutdown.

  5. close_sockets() Method:

  6. Iterates over _base_sockets and closes each socket using sock.close().
  7. Uses a try-except block to handle any potential errors during closure.

  8. run_server() Function:

  9. Creates an instance of CustomHTTPServer.
  10. Starts the server with server.serve_forever(), which handles requests until interrupted.
  11. On interruption, it calls server.shutdown(), ensuring all sockets are closed properly.

This solution ensures that when the server is stopped, either through a keyboard interrupt or other means, all associated sockets are gracefully closed, preventing resource leaks.


, , , ,