简体   繁体   中英

Python websockets client keep connection open

In Python, I'm using " websockets " library for websocket client.

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. 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?

I think your websocket is disconnected due to exit from context manager after 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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