Python Socket 获取连接结果

2024-04-19 15:15:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

在运行基准测试时,在出错之前,我会得到完全随机的好请求数,通常在4到500之间。在

编辑:我花了一段时间才弄明白,但问题出在sock.listen(5)。因为我使用的apache基准测试具有更高的并发性(5或更高),这会导致连接积压堆积,此时连接开始被套接字丢弃。在


Tags: selfipnonehttpservertimeportdef
1条回答
网友
1楼 · 发布于 2024-04-19 15:15:37

为什么不使用Python附带的SocketServer有什么原因呢?这样可以更好地处理局面。如果你想做HTTP的东西,BaseHTTPServer也提供了一个框架。在

相关问题 更多 >