【问题标题】:Python websockets client keep connection openPython websockets客户端保持连接打开
【发布时间】:2020-10-20 23:32:27
【问题描述】:

在 Python 中,我为 websocket 客户端使用“websockets”库。

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 保持打开状态并能够在以后发送和接收消息?

【问题讨论】:

    标签: python python-3.x websocket python-asyncio


    【解决方案1】:

    我认为您的 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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多