Python WebSockets客户端保持连接开放

3
在Python中,我正在使用“websockets”库作为websocket客户端。
import asyncio
import websockets

async def init_sma_ws():
    uri = "wss://echo.websocket.org/"
    async with websockets.connect(uri) as websocket:
        name = input("What's your name? ")

        await websocket.send('name')
        greeting = await websocket.recv()

问题在于客户端websocket连接一旦收到响应就会断开。我希望连接保持打开状态,以便稍后发送和接收消息。
我需要做哪些更改才能保持websocket连接打开并能够稍后发送和接收消息?
2个回答

4
我认为你的websocket由于退出上下文管理器后的recv()而断开连接。 以下代码可以完美运行:
import asyncio
import websockets


async def init_sma_ws():
    uri = "wss://echo.websocket.org/"
    async with websockets.connect(uri) as websocket:
        while True:
            name = input("What's your name? ")
            if name == 'exit':
                break

            await websocket.send(name)
            print('Response:', await websocket.recv())


asyncio.run(init_sma_ws())

-1
在您的方法中,您使用了异步上下文管理器,在代码块执行时关闭连接。在下面的示例中,使用了一个无限异步迭代器来保持连接打开状态。
import asyncio
import websockets


async def main():
    async for websocket in websockets.connect(...):
        try:
            ...
        except websockets.ConnectionClosed:
            continue


asyncio.run(main())

更多信息请参见库文档


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接