Python:如何关闭具有持久连接的线程化HTTP服务器(如何从另一个线程杀死readline()?

2024-09-29 23:22:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我将python2.6与HTTPServer和{}一起使用,它们将在一个单独的线程中处理每个请求。我还使用HTTP1.1persistent connections('Connection:keep alive'),因此服务器或客户端都不会在请求后关闭连接。在

下面是请求处理程序的大致情况

request, client_address = sock.accept()
rfile = request.makefile('rb', rbufsize)
wfile = request.makefile('wb', wbufsize)

global server_stopping
while not server_stopping:
    request_line = rfile.readline() # 'GET / HTTP/1.1'
    # etc - parse the full request, write to wfile with server response, etc
wfile.close()
rfile.close()
request.close()

问题是如果我停止服务器,仍有一些线程在等待rfile.readline()。在

我会在readline()上面放一个select([rfile, closefile], [], [])并在想关闭服务器时写入closefile,但我认为它在windows上不起作用,因为select只适用于套接字。在

我的另一个想法是跟踪所有正在运行的请求和rfile.close(),但是我遇到了断管错误。在

有什么想法?在


Tags: 服务器closereadlineserverrequestetc线程select
3条回答

就快到了,正确的方法是调用rfile.close(),捕捉断开的管道错误,并在发生这种情况时退出循环。在

如果在HTTPServer子类中将daemon_threads设置为true,则线程的活动不会阻止服务器退出。在

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    daemon_threads = True

您也可以通过使closefile成为一个套接字来解决Windows问题。毕竟,由于它可能是由主线程打开的,所以您可以决定是将其作为套接字还是文件打开;-)。在

相关问题 更多 >

    热门问题