首页 > 解决方案 > 将超时设置为python套接字连接recv方法

问题描述

我正在尝试编写一个简单的 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

最好的方法是什么?

标签: pythonpython-3.xsocketshttpnetworking

解决方案


推荐阅读