Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple python server using SimpleHTTPServer and SocketServer, how do I close the socket down before rerunning .py file?

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()
like image 374
Bentley4 Avatar asked May 16 '12 07:05

Bentley4


People also ask

How do you close a simple HTTP server in python?

To stop the server, I just press Ctrl+C.

What does python SimpleHTTPServer do?

The SimpleHTTPServer module is a Python module that enables a developer to lay the foundation for developing a web server. However, as sysadmins, we can use the module to serve files from a directory. The module loads and serves any files within the directory on port 8000 by default.

How do I fix an already used address in python?

You can easily clear the python socket error 48: Address already in use by specifying an unused port or freeing up the port that the process is bound to. If you get the error on Raspberry Pi, simply restart it to repair.


1 Answers

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.

like image 174
Nick Craig-Wood Avatar answered Nov 15 '22 15:11

Nick Craig-Wood