How to manually close a websocket

David542 picture David542 · Oct 7, 2018 · Viewed 7.4k times · Source

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. Here is what I have so far:

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

What should the last part of this be?

Answer

madjaoue picture madjaoue · Oct 8, 2018

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