社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

pythonwebsocket只从客户端接收一次

boomeran • 3 年前 • 300 次点击  

顾客

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


Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/99361
 
300 次点击  
文章 [ 1 ]  |  最新文章 3 年前
RedEyed
Reply   •   1 楼
RedEyed    3 年前

所以,你的 consumer_handler 接收一次消息并完成。
你需要添加循环。
试试这样的方法:

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