pythonpython-3.xwebsocketdjango-channels

How to manually close a websocket


If I'm not using a context for a websocket, how would I manually close it? When I try running conn.close() I get an event loop is closed error:

from asgiref.sync import async_to_sync
import websockets

# connect -- works OK
conn = async_to_sync(websockets.connect)("ws://localhost:8000/ws/registration/123/")

# send message -- works OK
async_to_sync(conn.send)("hello")

# disconnect -- doesn't work
async_to_sync(conn.close)()

Solution

  • You can use websocket-client library, it's already sync and pretty straightforward.

    Install

    pip install websocket-client

    Usage

    from websocket import create_connection
    ws = create_connection(someWsUrl)  # open socket
    ws.send(someMessage)  # send to socket
    ws.recv(nBytes)  # receive from socket
    ws.close()  # close socket