Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 281
David542 Avatar asked Oct 07 '18 20:10

David542


1 Answers

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
like image 193
madjaoue Avatar answered Oct 19 '22 18:10

madjaoue