[英]Python Websocket only receives once from client
I want to send values from a for loop from the client-server but the server only receives the first value and the connection is cut shortly我想从客户端服务器的 for 循环中发送值,但服务器只接收第一个值并且连接很快被切断
Client客户
import asyncio
import websockets
import time
async def message():
async with websockets.connect("ws://-------:5051") as socket:
for i in range(20):
await socket.send(f"{i}")
print(i)
time.sleep(4)
asyncio.get_event_loop().run_until_complete(message())
Server服务器
import asyncio
import websockets
async def consumer_handler(websocket,path):
client_type = await websocket.recv()
print(client_type)
start_server = websockets.serve(consumer_handler,"ws://-------:5051", 5051)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
So, your consumer_handler
receives message once and finishes.因此,您的
consumer_handler
收到一次消息并完成。
You need to add loop.您需要添加循环。
Try something like this:尝试这样的事情:
async def consumer_handler(websocket, path):
async for msg in websocket:
print(msg)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.