如何永远运行异步 websocket 客户端?

Del*_*lsx 3 python asynchronous websocket

我正在尝试为客户端使用 websocket。客户端发送一些启动消息,之后,他可以接收消息,无论何时发送或不发送。客户端是异步的,我从 doc 那里得到了一些代码,但我不知道我在做什么。

async def wsrun(uri):
    async with websockets.connect(uri) as websocket:
        await websocket.send('hey')
        print(await websocket.recv()) # Starts receive things, not only once

asyncio.get_event_loop().run_until_complete(wsrun('wss://localhost:1515'))
Run Code Online (Sandbox Code Playgroud)

问题是,websocket recv 只显示服务器发送的第一件事:(

dru*_*rum 6

虽然我不能帮助你的生活,试试这个:

async def wsrun(uri):
    async with websockets.connect(uri) as websocket:
        await websocket.send('hey')
        while True:
            print(await websocket.recv()) # Starts receive things, not only once

asyncio.get_event_loop().run_until_complete(wsrun('wss://localhost:1515'))
Run Code Online (Sandbox Code Playgroud)