HTTP服务器在接受数据包时挂起

时间:2012-04-04 01:35:27

标签: python http

我编写了一个简单的http服务器来处理POST请求:

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( )

服务器运行良好但有时它只是挂起。当我按 CTRL + C 时,它会出现以下错误,然后继续接收数据:

Exception happened during processing of request from ('1.1.1.2', 50928)
Traceback (most recent call last):
  File "/usr/lib/python2.6/SocketServer.py", line 281, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.6/SocketServer.py", line 307, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.6/SocketServer.py", line 320, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.6/SocketServer.py", line 615, in __init__
    self.handle()
  File "/usr/lib/python2.6/BaseHTTPServer.py", line 329, in handle
    self.handle_one_request()
  File "/usr/lib/python2.6/BaseHTTPServer.py", line 312, in handle_one_request
    self.raw_requestline = self.rfile.readline()
  File "/usr/lib/python2.6/socket.py", line 406, in readline
    data = self._sock.recv(self._rbufsize)
KeyboardInterrupt

有人可以告诉我如何纠正这个问题吗?我无法理解错误。

1 个答案:

答案 0 :(得分:11)

我完全重写了我的解决方案以解决两个缺点:

  • 即使客户端仅打开了连接但未开始通信,它也可以处理超时。
  • 如果客户端打开连接,则会分叉新的服务器进程。慢客户端无法阻止其他客户端。

它尽可能基于您的代码。它现在是一个完整的独立演示。如果您在http://localhost:8000/上打开浏览器并将'模拟错误'写入表单并按提交,则会模拟运行时错误。

import BaseHTTPServer
import SocketServer
import cgi


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)
                assert postvars.get('foo', '') != ['simulate error']
            body = 'Something'
            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:
            self.send_error(500)
            raise

    def do_GET(self):
        # demo for testing POST by web browser - without valid html
        body = 'Something\n<form method="post" action="http://%s:%d/">\n' \
                '<input name="foo" type="text"><input type="submit"></form>\n'\
                % self.server.server_address
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


class ForkingHTTPServer(SocketServer.ForkingMixIn, BaseHTTPServer.HTTPServer):
    def finish_request(self, request, client_address):
        request.settimeout(30)
        # "super" can not be used because BaseServer is not created from object
        BaseHTTPServer.HTTPServer.finish_request(self, request, client_address)


def httpd(handler_class=MyHandler, server_address=('localhost', 8000)):
    try:
        print "Server started"
        srvr = ForkingHTTPServer(server_address, handler_class)
        srvr.serve_forever()  # serve_forever
    except KeyboardInterrupt:
        srvr.socket.close()

if __name__ == "__main__":
    httpd()

可以禁用分叉,例如通过从代码中删除类SocketServer.ForkingMixIn来进行调试。