线程化,非阻塞的websocket客户端

发布于 2021-01-29 18:08:25

我想在Python中运行一个程序,该程序每秒通过Web套接字向Tornado服务器发送一条消息。我一直在websocket-client上使用该示例;

该示例不起作用,因为ws.run_forever()它将停止while循环的执行。

有人可以给我一个例子,说明如何正确地将其实现为线程类,我既可以调用它的send方法,又可以接收消息?

import websocket
import thread
import time

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    pass

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_error = on_error, on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

    while True:
        #do other actions here... collect data etc.
        for i in range(100):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
关注者
0
被浏览
154
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    在他们的github页面上有一个例子可以做到这一点。好像您是从该示例开始的,并从 on_open中每秒 发送一次消息的代码并在 run_forever
    调用之后粘贴了该 代码 ,BTW一直运行到套接字断开连接为止。

    也许您在这里对基本概念有疑问。总会有一个专用于侦听套接字的线程(在这种情况下,主线程在 run_forever
    内部进入循环以等待消息)。如果您想进行其他操作,则需要另一个线程。

    下面是示例代码的不同版本,其中不是使用主线程作为“套接字侦听器”,而是创建了另一个线程,并在 其中 运行 run_forever
    。我认为它有点复杂,因为您可以编写代码来确保套接字可以连接,同时可以使用 on_open 回调,但这也许可以帮助您理解。

    import websocket
    import threading
    from time import sleep
    
    def on_message(ws, message):
        print message
    
    def on_close(ws):
        print "### closed ###"
    
    if __name__ == "__main__":
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_close = on_close)
        wst = threading.Thread(target=ws.run_forever)
        wst.daemon = True
        wst.start()
    
        conn_timeout = 5
        while not ws.sock.connected and conn_timeout:
            sleep(1)
            conn_timeout -= 1
    
        msg_counter = 0
        while ws.sock.connected:
            ws.send('Hello world %d'%msg_counter)
            sleep(1)
            msg_counter += 1
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看