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