python websocet回调_python – 线程,非阻塞websocket客户端
他們的 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 websocet回调_python – 线程,非阻塞websocket客户端的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java h5在线音频_用h5 audi
- 下一篇: 《跟我学java》_《跟我学Java——