我正在尝试计算从给定套接字接收所有数据所需的时间,因此我使用“with Timeout(5, False)”等待 5 秒的数据,然后保存最后一次接收的时间。但是,当我提供多个线程时,当前的代码只会停滞不前。我想帮助弄清楚为什么它应该在超时时挂起。
#!/usr/bin/env python
import sys
import time
from gevent import socket, Timeout
from gevent.pool import Pool
def calc_wait(website):
data = ''
start = stop = time.time()
sock_buffer = ''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((website,80))
s.send('HEAD / HTTP/1.1\n\n')
with Timeout(5, False):
while True:
data = s.recv(1024)
if data:
sock_buffer += data
stop = time.time()
print ('Recieved {0} bytes in {1} seconds from {2}'
.format(len(sock_buffer), stop-start, s.getpeername()))
return 0
if __name__ == "__main__":
targs = ['google.com', 'yahoo.com', 'bing.com',\
'tide.com', 'monkey.com', 'python.com',\
'a.com', 'b.com', 'c.com', 'd.com']
pool = Pool(10)
for t in targs:
pool.spawn(calc_wait, t)
pool.join()