SocketServer question
Jordan Krushen
jordan at krushen.com
Sat Feb 15 16:06:57 EST 2003
Nagy László wrote:
> Another important question: when I call server.handle_request() it
> will block until
> an incoming connection arrives. Meanwhile there can be other handler
> threads running.
> This way I'm unable to stop the server because the main thread is
> blocked. Is there
> a way to give a timeout for handle_request so I can preiodically check
> if it is time
> to stop the server? If not, how can I stop the server gracefully?
> (I would like to stop or restart the server using a client connected
> to it.)
This is what I do: by wrapping the call to handle_request with
select.select(), you can achieve a simple timeout. Simply calling this
thread's join() method will set the flag, and within a second the select
call will timeout and not re-enter the loop, and finish.
---
class Server(ThreadingMixIn, HTTPServer):
def __init__(self):
HTTPServer.__init__(self, ("0.0.0.0", 80), reqHandler)
class httpdThread(Thread):
def __init__(self, timeout=1):
self.timeout = timeout
self._stopevent = Event()
Thread.__init__(self)
def run(self):
svr = Server()
svrfd = svr.fileno()
while not self._stopevent.isSet():
ready = select.select([svrfd], [], [], self.timeout)
if svrfd in ready[0]:
svr.handle_request()
def join(self, timeout=None):
self._stopevent.set()
Thread.join(self, timeout)
More information about the Python-list
mailing list