我正在使用 Tornado 运行 WebSocketHandler,并且while
在 Handler 中有一个循环。这个循环阻塞了一切——这很糟糕。如何使tailstream()
函数异步(又名非阻塞)?(就像现在一样,tailstream
阻止一切,甚至无法建立新的 websocket 连接。我需要它为每个 websocket 连接运行。)
(...)
class WSHandler(tornado.websocket.WebSocketHandler):
connections = []
filters = {}
def allow_draft76(self):
# for iOS 5.0 Safari
return True
def open(self):
self.write_message('open')
self.count = db.my_collection.count() - 1
self.cursor = coll.find(tailable=True, await_data=True, skip=self.count)
self.tailstream()
def on_message(self, message):
print message
def on_close(self):
self.connections.remove(self)
self.cb.stop()
print 'connection closed'
@tornado.web.asynchronous
def tailstream(self):
while self.cursor.alive:
try:
doc = self.cursor.next()
self.print2web(doc)
except StopIteration:
time.sleep(1)
(...)