我是龙卷风的新手。我正在尝试使用龙卷风构建聊天服务器代理,我从网络客户端收到消息,通常只需要将其发送回去,但是,我需要先将这些消息发送到另一台服务器,问题来了,等待其他服务器响应花费很多时间,我需要使其无阻塞,但是当我使用龙卷风的匿名方法时,它根本不起作用,请帮帮我,谢谢你好!
那是我的伪代码的一部分:
class ClientWSConnectienter(websocket.WebSocketHandler):
_thread_pool = ThreadPoolExecutor(20)
def initialize(self, room_handler):
#chat room initiate
self.__rh = room_handler
@run_on_executor(executor='_thread_pool')
def worker(self,msg):
#send the msg to another server
pmessage=send_msg_to_server(msg)
return pmessage
@tornado.web.asynchronous
@tornado.gen.coroutine
def on_message(self, message):
#this will blocking for too much time,and I want make it no-blocking
pmessage=yeild worker(msg)
#send the recive pmessage to others client
room.write_message(pmessage)
self.finish()
显然,它不起作用,我得到这样的东西:
error:websocket cannot use this method
所以我该怎么做?非常感谢
但是我重新编辑代码后,它仍然在任务部分中阻塞。我不知道为什么,这仍然是我的代码的一部分
重新编辑:
class ClientWSConnection(websocket.WebSocketHandler):
def initialize(self, room_handler):
self.queue = tornado.queues.Queue()
def open(self, client_id):
IOLoop.current().spawn_callback(self.loop)
def on_message(self, message):
self.queue.put(msg)
def on_close(self):
self.queue.put(None)
@coroutine
def loop(self):
while 1:
msg=yield self.queue.get()
if msg is None:
return
msg=yield self.worker(msg)
pmessage = msg
room.write_message(pmessage)
@coroutine
def worker(self,msg):
#need to send the other server,blocking here
time.sleep(10)
raise Return(msg)
最佳答案
我认为该错误消息来自您对finish()
的调用,这对于websockets没有意义(您是说close()
吗?)。 (此外,无需同时使用@asynchronous
和@coroutine
;仅@coroutine
就足够了)
但是还有一个更大的问题:请记住,当重写超类中定义的方法时,只有在文档说明可以的情况下,才可以将它们作为协程(因为协程的名称不同于常规方法)。 WebSocketHandler.on_message
当前(从Tornado 4.3开始)不支持协程。
因此,您需要使用队列将其交给其他任务。像这样:
class MyHandler(WebSocketHandler):
def initialize(self):
self.queue = tornado.queues.Queue()
def on_open(self):
IOLoop.current().spawn_callback(self.loop)
def one_message(self, msg):
self.queue.put(msg)
def on_connection_close(self):
self.queue.put(None)
@coroutine
def loop(self):
while True:
msg = yield self.queue.get()
if msg is None:
return
pmessage = yield self.worker(msg)
self.write_message(pmessage)