Question

I am creating a ForkingTCPServer to act as a proxy. It handles perfectly fine, but will not release the socket after executing. I have already tried .shutdown() and .server_close() but they just cause the program to freeze up. How can I release the socket so that it can be used again?

import SocketServer
import SimpleHTTPServer
import urllib

PORT = 8080

class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.copyfile(urllib.urlopen("http://"+self.path[1:]), self.wfile)

httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
print "serving at port", PORT
httpd.handle_request()
Was it helpful?

Solution

The handle_request method handles only one request, so the parent process answers only one request.

You can put the calls to handle_request in a loop.

Otherwise, if you mean the fact that you get an "in use" error when you fire up a new copy of the server, that's because you have to wait for the TCP 2MSL timer to time out. To work around that, set SO_REUSEADDR on the listening socket. (Set self.allow_reuse_address, although I'm not quite sure where to set it, having not done that.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top