如果我没有为websocket使用上下文,我将如何手动关闭它?当我尝试运行conn.close()时,出现event loop is closed
错误。这是我到目前为止的内容:
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)()
这最后一部分应该是什么?
答案 0 :(得分:2)
您可以使用websocket-client库,它已经同步并且非常简单。
安装
pip install websocket-client
用法
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