繁体   English   中英

Python Websocket 只从客户端接收一次

[英]Python Websocket only receives once from client

我想从客户端服务器的 for 循环中发送值,但服务器只接收第一个值并且连接很快被切断

客户

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()) 

服务器

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()


因此,您的consumer_handler收到一次消息并完成。
您需要添加循环。
尝试这样的事情:

async def consumer_handler(websocket, path):
    async for msg in websocket:
        print(msg)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM