Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to test websocket availability in python

I am using the following code to test that a local websocket server is running:

import asyncio
import websockets

async def hello():
    async with websockets.connect('ws://127.0.0.1:8000/ws/registration/123') as websocket:
        await websocket.send(json_data)

asyncio.get_event_loop().run_until_complete(hello())

Is there a simpler way to do this without using asyncio? Something such as:

import asyncio
import websockets

conn = websockets.connect('ws://127.0.0.1:8000/ws/registration/123')
conn.send('hello')

Basically, I'm just trying to find the simplest way to test to see if my websocket server is listening and receiving messages at a particular url.

like image 201
David542 Avatar asked Jan 17 '26 00:01

David542


1 Answers

Doesn't async_to_sync make this more complex? Why not just create a normal test_url function:

def test_url(url, data=""):
    async def inner():
        async with websockets.connect(url) as websocket:
            await websocket.send(data)
    return asyncio.get_event_loop().run_until_complete(inner())

test_url("ws://127.0.0.1:8000/ws/registration/123")
like image 89
Sraw Avatar answered Jan 19 '26 14:01

Sraw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!