![](/img/trans.png)
[英]How to call Python Tornado Websocket Server inside another Python
[英]bottleneck in python tornado websocket server
我有一個用python龍卷風編寫的websocket服務器。 服務器將接收來自客戶端的許多連接,並且您知道,我們有on_message
函數,該函數會在收到on_message
消息時觸發。 因此,這是我的問題,如果一條消息(例如來自客戶端的請求)需要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
我主要使用Tornado托管我的Web應用程序,因此我可以告訴您,如果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
裝飾器將其包裝
這個問題和你的相似。 答案也是有益的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.