Python websockets client keep connection open

Viewed 1481

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?

1 Answers

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