我复制了websocket client code ..它有效,除了它在打印Hello 1..Hello 2和Hello 3之后退出,然后它退出。我认为run_forever意味着它将永远运行,那为什么它会退出?如何让程序继续等待websocket消息?
import thread
import pdb
import websocket
import time
import requests
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run(*args):
for i in range(3):
time.sleep(1)
ws.send("Hello %d" % i)
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
if __name__ == "__main__":
URL = "http://127.0.0.1:8000/login/"
client = requests.session()
EMAIL = "u234234"
PASSWORD = "t234ri3234221"
login_data = dict(username=EMAIL, password=PASSWORD)
r = client.post(URL, data=login_data, headers=dict(Referer=URL))
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:8080/",
on_message = on_message,
on_error = on_error,
on_close = on_close,
)
ws.on_open = on_open
ws.run_forever()
答案 0 :(得分:1)
我不能声称在python中使用websockets非常了解,但通常在关闭套接字时也会关闭关联的连接。因此,为了保持连接打开,我想您可能想尝试从on_open函数中删除ws.close()行。