将超时设置为python套接字连接recv方法

时间:2018-10-26 16:12:09

标签: python python-3.x sockets http networking

我正在尝试编写一个简单的http服务器。我希望它对Connection: keep-alive标头起作用,所以我想确保connection.recv()会超时。我尝试了socket.settimeout(timeout)方法,但是即使收到数据,它也会在timeout时间后关闭连接。我想要的是这样的:

while True:
    try:
        #start to wait for timeout seconds
        request = conn.recv(256, timeout)
        process()
        #if there is no keep-alive header end the operation
        if "keep-alive" not in request:
            conn.close()
            break
        else:
            #if there was a keep alive header start getting the data
            continue
    except:
        #this means timeout seconds passed after recv() was called
        conn.close()
        break

做这件事的最好方法是什么?

0 个答案:

没有答案