9

When I run my python server file simplehttpwebsite.py in the linux shell and I do control+c and run it again I get socket.error: [Errno 98] Address already in use.

How do I make sure the socket closes down when I do ctrl+c?

simplehttpwebsite.py

#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)

server.serve_forever()
Bentley4
  • 10,678
  • 25
  • 83
  • 134

1 Answers1

12

Here is how you do it

#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
class MyTCPServer(SocketServer.TCPServer):
    allow_reuse_address = True
server = MyTCPServer(('0.0.0.0', 8080), Handler)

server.serve_forever()

IMHO this isn't very well documented, and it should definitely be the default.

Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132