简体   繁体   English

Python websockets 客户端保持连接打开

[英]Python websockets client keep connection open

In Python, I'm using " websockets " library for websocket client.在 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()

The problem is the client websocket connection is disconnected once a response is received.问题是一旦收到响应,客户端 websocket 连接就会断开。 I want the connection to remain open so that I can send and receive messages later.我希望连接保持打开状态,以便稍后可以发送和接收消息。

What changes do I need to keep the websocket open and be able to send and receive messages later?我需要做哪些更改才能使 websocket 保持打开状态并能够在以后发送和接收消息?

I think your websocket is disconnected due to exit from context manager after recv() .我认为您的 websocket 由于在recv()之后退出上下文管理器而断开连接。 Such code works perfectly:这样的代码完美地工作:

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

In your approach you used a asynchronous context manager which closes a connection when code in the block is executed.在您的方法中,您使用了异步上下文管理器,它在执行块中的代码时关闭连接。 In the example below an infinite asynchronous iterator is used which keeps the connection open.在下面的示例中,使用了一个无限异步迭代器来保持连接打开。

import asyncio
import websockets


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


asyncio.run(main())

More info in library's docs . 图书馆文档中的更多信息。

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

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