如何手动关闭 websocket
How to manually close a websocket
如果我没有使用 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)()
最后一部分应该是什么?
您可以使用 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
如果我没有使用 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)()
最后一部分应该是什么?
您可以使用 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