当我尝试telnet到服务器时,代码从未到达print 'never reach1'
或print 'never reach2'
行。
import sys, signal
from gevent.server import StreamServer
from gevent.pool import Pool
from gevent import monkey
import gevent
from gevent import Timeout
import random
class SocketPool(object):
def __init__(self):
self.pool = Pool(1000)
def listen(self, socket):
while True:
line = socket.recv(1024)
print line
def add_handler(self, socket, address):
if self.pool.full():
raise Exception("At maximum pool size")
else:
self.pool.spawn(self.listen, socket)
gevent.spawn(self.wait).join()
def wait(self):
try:
timeout = Timeout(1)
timeout.start()
except Timeout:
print 'never reach1'
except:
print 'never reach2'
def shutdown(self): self.pool.kill()
def signal_handler(signal, frame): sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
monkey.patch_all()
sockPool = SocketPool()
server = StreamServer(('127.0.0.1', 5000), sockPool.add_handler)
server.serve_forever()
从文档中可以看到:
timeout = Timeout(seconds, exception)
timeout.start()
try:
... # exception will be raised here, after *seconds* passed since start() call
finally:
timeout.cancel()
所以你的try
块被完全执行,因此不能捕获异常。您应该使用while
循环或至少需要1秒才能看到异常的计算。
如果你想让一个方法,简单地"睡眠"不使用CPU,我建议使用一个简单的time.sleep
,而不是使用Timeout
。