代码之家  ›  专栏  ›  技术社区  ›  Ian Baget

Python套接字获取连接重置

  •  1
  • Ian Baget  · 技术社区  · 16 年前

    我创建了一个线程套接字侦听器,它将新接受的连接存储在队列中。然后,套接字线程从队列中读取并响应。出于某种原因,当使用“ab”(apache benchmark)使用2或更多的并发性进行基准测试时,我总是在它能够完成基准测试之前重置连接(这是在本地进行的,因此没有外部连接问题)。

    class server:    
    _ip = ''
    _port = 8888
    
    def __init__(self, ip=None, port=None):
        if ip is not None:
            self._ip    = ip
        if port is not None:
            self._port  = port
        self.server_listener(self._ip, self._port)
    
    def now(self):
        return time.ctime(time.time())
    
    def http_responder(self, conn, addr):
        httpobj = http_builder()
        httpobj.header('HTTP/1.1 200 OK')
        httpobj.header('Content-Type: text/html; charset=UTF-8')
        httpobj.header('Connection: close')
        httpobj.body("Everything looks good")        
        data = httpobj.generate()
    
        sent = conn.sendall(data)
    
    
    def http_thread(self, id):        
        self.log("THREAD %d: Starting Up..." % id)
    
        while True: 
            conn, addr = self.q.get()
            ip, port = addr
            self.log("THREAD %d: responding to request: %s:%s - %s" % (id, ip, port, self.now()))
            self.http_responder(conn, addr)                
            self.q.task_done()
            conn.close()
    
    def server_listener(self, host, port):
        self.q = Queue.Queue(0)
    
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind( (host, port) )
        sock.listen(5)
    
    
        for i in xrange(4): #thread count
            thread.start_new(self.http_thread, (i+1, ))
    
        while True:
            self.q.put(sock.accept())
    
        sock.close()
    
    server('', 9999)
    

    编辑:我花了一段时间才弄明白,但问题出在 sock.listen(5)

    1 回复  |  直到 16 年前
        1
  •  0
  •   Lee    16 年前

    有没有理由不使用Python附带的SocketServer?这样可以更好地处理这种情况。如果你想做HTTP的事情,BaseHTTPServer也提供了一个框架。