我正在使用 Tornado 运行 WebSocketHandler,并且我在处理程序中有一个 while
循环。这个循环阻止了一切——这非常糟糕。如何使 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)
(...)
最佳答案
我认为 while
不会阻止它。但是 time.sleep
可以!
将其替换为 yield gen.Task(IOLoop.instance().add_timeout, time.time() + 5)
来自 answer .
如果它没有帮助 - 我们可以考虑解决方案的整体结构。
关于python - 如何在 Tornado.WebSocket 类中异步运行循环函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12664306/