[英]Python websockets fast one way but 10x slower with response
I have a sanic webserver running websockets, behind the scenes its using the "websockets" library.我有一个运行 websockets 的 sanic 网络服务器,在幕后它使用“websockets”库。
Server服务器
from asyncio import sleep
from sanic import Sanic
app = Sanic("websocket test")
@app.websocket("/")
async def test(_, ws):
while True:
data = await ws.recv()
data = await ws.send('Hi')
if __name__ == "__main__":
app.run(host="127.0.0.1", port=8000)
Client客户
import asyncio
import websockets
async def hello():
uri = "ws://localhost:8000"
async with websockets.connect(uri) as websocket:
while iteration:
await websocket.send("Hi")
await websocket.recv()
asyncio.get_event_loop().run_until_complete(hello())
When I remove ws.send('Hi')
from the server and await websocket.recv()
from the client i can get 58000 messages a second, once I start listening for a response it goes all the way down to 6000 messages a second, I am just curious what is making this run 10x slower when the server responds.当我从服务器删除ws.send('Hi')
并从客户端await websocket.recv()
时,我每秒可以收到 58000 条消息,一旦我开始监听响应,它就会一直下降到每秒 6000 条消息,我只是好奇是什么让服务器响应时运行速度慢了 10 倍。
I think the solution here would be to seperate your send
and recv
into seperate tasks so they can yield concurrently.我认为这里的解决方案是将您的send
和recv
分成单独的任务,以便它们可以同时产生。
async def producer(send):
while True:
await send("...")
await asyncio.sleep(1)
async def consumer(recv):
while True:
message = await recv
print(message)
async def test(request, ws):
request.app.add_task(producer(ws.send)))
request.app.add_task(consumer(ws.recv))
Obviously, this is a very simple example, and at the very least you should use some sort of a Queue
for your producer.显然,这是一个非常简单的例子,至少你应该为你的生产者使用某种Queue
。
But, when you break them into seperate tasks, then your recv
is not blocked by send
.但是,当您将它们分解为单独的任务时,您的recv
不会被send
阻止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.