4

我想编写一个应用程序,其中主线程启动一个 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

4

0 回答 0