线程,非阻塞websocket客户端

时间:2015-03-19 13:08:10

标签: python multithreading websocket

我想在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)

1 个答案:

答案 0 :(得分:15)

他们的github page中有一个例子就是这样。看起来你从那个例子开始并从 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