python - 线程化、非阻塞的 websocket 客户端

标签 python multithreading websocket

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

这个例子不起作用,因为ws.run_forever()会停止while循环的执行。

谁能给我一个例子,说明如何将其正确实现为线程类,我既可以调用其发送方法,又可以接收消息?

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)

最佳答案

在他们的 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

关于python - 线程化、非阻塞的 websocket 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29145442/

相关文章:

python - 将变量值附加到谷歌表格中的特定列

php - 在亚马逊EC2上运行websocket服务器

java - 如何使用多线程调用多个服务?

nginx - 带有 nginx 的 Django channel 客户端没有收到消息

node.js - 获取 Kue 作业的结果并通过开放连接将其推送给客户端

python - 如何使用python向MySQL表中添加记录?

python - 将两个字典(价格、股票)的值相乘然后相加

python - 从行中的多个值计算一个值

java - Java中的线程不是同时启动的,而是顺序启动的

java - 不同的 (HotSpot) JVM 线程类型有什么作用?