Python 线程化、非阻塞websocket客户端
我想用Python运行一个程序,每秒通过web套接字向Tornado服务器发送一条消息。我一直在使用websocket客户端上的示例 此示例不起作用,因为Python 线程化、非阻塞websocket客户端,python,multithreading,websocket,Python,Multithreading,Websocket,我想用Python运行一个程序,每秒通过web套接字向Tornado服务器发送一条消息。我一直在使用websocket客户端上的示例 此示例不起作用,因为ws.run\u forever()将停止while循环的执行 有人能给我一个例子,说明如何将它正确地实现为一个线程类,我既可以调用的send方法,也可以接收消息 import websocket import thread import time def on_message(ws, message): print message
ws.run\u 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)
他们的书中有一个例子就是这样的。看起来你是从这个例子开始的,把每秒发送消息的代码从on_open中取出,并在run_forever调用后粘贴,顺便说一句,它一直运行到套接字断开为止 也许你对这里的基本概念有疑问。总有一个线程专用于监听套接字(在本例中,主线程进入run_内部的循环,永远等待消息)。如果你想有其他事情发生,你需要另一个线程 下面是他们示例代码的另一个版本,不再使用主线程作为“套接字侦听器”,而是创建另一个线程,并在那里永远运行run_。我认为这有点复杂,因为您必须编写代码来确保套接字已连接,而您可以使用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
然后整个服务器在一个线程中运行?如果这个线程饱和了怎么办?@Paul:你说的“饱和”是什么意思?我的意思是,如果它使用多个线程,它每秒可以处理更多的数据。对于一个线程,我觉得您没有使用整个CPU,而且该线程可能会相对较快地被数据淹没。@Paul-在不涉及等待的情况下,线程不会提高效率;最后,GIL确保您仍然运行的单线程python绝对不是多线程的。如果您想要处理大量连接,那么应该使用异步IO和多处理将消息传递给其他执行该工作的进程。当您想要将结果返回给客户机时,可以将其填充到一个应答队列中,该队列由主异步IO进程拾取并返回