我想编写一个应用程序,其中主线程启动HTTP服务器,必须等待一个HTTP请求最多10秒。在收到(并处理)请求或超出超时之前,必须阻止应用程序。
我尝试使用此代码:
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
s.wfile.write("<html><head><title>Title</title></head>")
httpd = BaseHTTPServer.HTTPServer(('', 8001), RequestHandler)
httpd.socket.settimeout(10)
httpd.handle_request()
问题是,当服务器收到请求时,我收到以下错误消息:
Exception happened during processing of request from ('127.0.0.1', 51321)
Traceback (most recent call last):
File "C:\Python27\lib\SocketServer.py", line 284, in _handle_request_noblock
self.process_request(request, client_address)
File "C:\Python27\lib\SocketServer.py", line 310, in process_request
self.finish_request(request, client_address)
File "C:\Python27\lib\SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python27\lib\SocketServer.py", line 639, in __init__
self.handle()
File "C:\Python27\lib\BaseHTTPServer.py", line 343, in handle
self.handle_one_request()
File "C:\Python27\lib\BaseHTTPServer.py", line 313, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "C:\Python27\lib\socket.py", line 476, in readline
data = self._sock.recv(self._rbufsize)
error: [Errno 10035] A non-blocking socket operation could not be completed immediately
如果我删除settimeout函数,我没有收到此错误,但我也失去了超时。我也尝试使用setblocking函数,但它会破坏settimeout的效果。
我如何实现目标?
PS。:我在64位Windows 7上使用Python 2.7.2