首页 > 解决方案 > python tornado websocket服务器的瓶颈

问题描述

我有一个用 python tornado 编写的 websocket 服务器。服务器将接收来自客户端的许多连接,如您所知,我们有on_message在收到 websocket 消息时触发的函数。所以,这是我的问题,如果一条消息(比如来自客户端的请求)需要 5 秒来处理,那么当服务器正在处理一些请求时,服务器会进入阻塞模式并且不能接受或接收更多的连接或数据。经过一些研究,我发现Asyncio可以解决我的问题,但我现在不知道如何使用它。那么,我如何调用process方法以避免阻塞?

以下是我的代码:

class WavesClient(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True
    def open(self):
        print("New client connected")

   def on_message(self, message):
        self.process(message)

   def on_close(self):
        print("Client disconnected")
   def process(self,message):
        #it takes 5 sec to complete

标签: pythonasynchronouswebsockettornado

解决方案


我主要使用 tornado 来托管我的 webapps,因此我可以告诉你,如果你在 tornado 中的任何部分代码被阻塞,整个服务器都会被阻塞。

现在到您的代码:

@tornado.gen.coroutine
def on_message(self, message):
    process_results = yield self.process(message)
    self.write_message(process_results)

@tornado.gen.coroutine
def process(self, message):
    # a long process, this is the equivalent of time.sleep(2) which is blocking
    yield tornado.gen.sleep(2)
    return 'finished'

tornado你必须从yield一个函数中获取返回值。此外,如果您的函数正在产生,则必须使用tornado.gen.coroutine装饰器包装它

这个问题和你的类似。答案也很丰富。


推荐阅读