title: Shutting down gracefully from ThreadingTCPServer
body: <p>I've created a simple test app (Python 2.6.1) that runs a ThreadingTCPServer, based on the example <a href="http://danieldandrada.blogspot.com/2007/09/python-socketserverthreadingtcpserver.html" rel="nofollow noreferrer">here</a>.  If the client sends a command "bye" I want to shut down the server and exit cleanly from the application.  The exit part works OK, but when I try to re-run the app, I get:</p>
  
  <pre><code>socket.error: [Errno 48] Address already in use
  </code></pre>
  
  <p>I tried the solution given <a href="https://stackoverflow.com/questions/2274320/socketserver-threadingtcpserver-cannot-bind-to-address-after-program-restart">here</a> for setting the socket options but that didn't seem to help.  I've tried various ways to close the server down, but always get the same error.  </p>
  
  <p>Any idea what I'm doing wrong?</p>
  
  <pre><code>import SocketServer
  import socket
  import sys
  import threading
  import time
  
  class RequestHandler(SocketServer.BaseRequestHandler):
  
      def setup(self):
          print("Connection received from %s" % str(self.client_address))
          self.request.send("Welcome!\n")
  
      def handle(self):
          while 1:
              data = self.request.recv(1024)
              if (data.strip() == 'bye'):
                   print("Leaving server.")
                   self.finish()
                   self.server.shutdown()
                   # None of these things seem to work either
                   #time.sleep(2)
                   #del self.server.socket
                   #self.server.socket.shutdown(socket.SHUT_WR)
                   #self.server.socket.close()
                   #self.server.server_close()
                   break
  
  
      def finish(self):
          self.request.send("Goodbye!  Please come back soon.")
  
  if __name__ == "__main__":
         server = SocketServer.ThreadingTCPServer(("localhost", 9999), RequestHandler)
         # This doesn't seem to help.
         #server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
         #server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         server.serve_forever()
         print("Exiting program.")
  </code></pre>