Py学习  »  tornado

python tornado websocket服务器瓶颈

Mehrdad Dadvand • 5 年前 • 1136 次点击  

我有一个用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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/35378
 
1136 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Therenca
Reply   •   1 楼
Therenca    5 年前

我主要使用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 装饰工

这个 question 和你的相似。答案也很有用。