代码之家  ›  专栏  ›  技术社区  ›  David542

如何手动关闭websocket

  •  3
  • David542  · 技术社区  · 6 年前

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

    1 回复  |  直到 6 年前
        1
  •  4
  •   madjaoue    6 年前

    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