1
class MyHandler( BaseHTTPServer.BaseHTTPRequestHandler):
    def do_POST( self ):
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        postvars = {}
        try:
          if ctype == 'application/x-www-form-urlencoded':
              length = int(self.headers.getheader('content-length'))
              postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)

          self.send_response( 200 )
          self.send_header( "Content-type", "text")
          self.send_header( "Content-length", str(len(body)) )
          self.end_headers()
          self.wfile.write(body)
        except:
          print "Error"


def httpd(handler_class=MyHandler, server_address = ('2.3.4.5', 80)):
    try:
        print "Server started"
        srvr = BaseHTTPServer.HTTPServer(server_address, handler_class)
        srvr.serve_forever() # serve_forever
    except KeyboardInterrupt:
        server.socket.close()


if __name__ == "__main__":
    httpd( )

我已经准备好大部分代码。如果客户端处于非活动状态或在 10 秒内没有响应(类似于https://stackoverflow.com/a/265741/204623),我需要添加关闭连接的代码。基本上我不希望服务器不阻止对 send_response()、wfile.write() 等的调用。我该怎么做?

4

1 回答 1

3

尝试这个:

import BaseHTTPServer

class TimeoutServer(BaseHTTPServer.HTTPServer):
    def get_request(self):
        result = self.socket.accept()
        result[0].settimeout(10)
        return result

然后使用TimeoutServer类代替HTTPServer来获得超时支持。

于 2012-04-30T05:10:42.680 回答