Skip to content Skip to sidebar Skip to footer

Socket Threads Hang In Timeout Block

I'm trying to calculate the time it takes to receive all data from a given socket, so I'm using 'with Timeout(5, False)' to wait 5 seconds for data and then save the time of last r

Solution 1:

The problem is not that the socket hangs but that you never break when the socket ends, creating an infinite loop. Here's the code needed to fix it:

with Timeout(5, False):
    while1:
        data = s.recv(1024)
        if not data:
            break

        sock_buffer += data
        stop = time.time()

EDIT: Once the socket completes its connection, it won't yield the greenlet thread even though you're calling #recv. So if you want the timeout to be able to fire you need to manually yield with gevent.sleep():

with Timeout(5, False):
    whileTrue:
        data = s.recv(1024)
        if data:
            sock_buffer += data
            stop = time.time()

        gevent.sleep()

From the gevent docs: "Calling sleep with seconds of 0 is the canonical way of expressing a cooperative yield."

Post a Comment for "Socket Threads Hang In Timeout Block"