Simple way to test websocket availability in python

Question:

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.

Asked By: David542

||

Answers:

You can do the above by using async_to_sync, for example:

from asgiref.sync import async_to_sync
import websockets

def test_url(url, data=""):
    conn = async_to_sync(websockets.connect)(url)
    async_to_sync(conn.send)(data)


test_url("ws://127.0.0.1:8000/ws/registration/123")

Note that the “handshake” will probably not complete here because it needs to be accepted both ways, but the above should enable you to test to make sure that the urls are being routed properly, etc.

Answered By: David542

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")
Answered By: Sraw

if you need to disable cert verification, you can do this:

#!/usr/bin/env python3 


import asyncio
import ssl
import websockets 

def test_url(url, data=""):
    async def inner():
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        async with websockets.connect(url, ssl=ctx) 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")


Answered By: jeremy mordkoff
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.