【问题标题】:why does my program quit and not run forever为什么我的程序退出并且不能永远运行
【发布时间】:2015-02-02 21:43:11
【问题描述】:

我复制了一个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()

【问题讨论】:

  • 源码说明只要socket可用就运行

标签: python node.js websocket


【解决方案1】:

我不能声称非常了解在 python 中使用 websockets,但一般来说,当你关闭一个套接字时,你也会关闭相关的连接。因此,为了保持连接打开,我认为您可能想尝试从 on_open 函数中删除 ws.close() 行。

【讨论】:

  • 感谢您的回复。我希望 thread.start_new_thread(run, ()) 开始另一个运行.. 不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 2011-03-12
  • 2015-01-18
  • 1970-01-01
  • 2016-09-07
  • 2013-08-25
  • 1970-01-01
相关资源
最近更新 更多