相关疑难解决方法(0)

线程,非阻塞websocket客户端

我想在Python中运行一个程序,它每秒通过Web套接字向Tornado服务器发送一条消息.我一直在websocket-client上使用这个例子;

此示例不起作用,因为ws.run_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)
Run Code Online (Sandbox Code Playgroud)

python multithreading websocket

12
推荐指数
1
解决办法
2万
查看次数

sys.exit对多线程有什么作用?

我对python中的sys.exit()感到很困惑.在python文档中,它说"退出Python"; 这是否意味着sys.exit()在python程序中调用时,进程将退出?如果是这样,下面的代码显示了不同的结果:

import sys
import time
import threading

def threadrun():
    while(True):
        time.sleep(1)

if __name__=="__main__":
    t=threading.Thread(target=threadrun)
    t.start()
    sys.exit()
Run Code Online (Sandbox Code Playgroud)

在Linux中启动这个程序,结果不是python文档说的那个预期的,但仍然在系统中运行,那么sys.exit()真正做到了什么?

python multithreading exit

11
推荐指数
2
解决办法
1660
查看次数

标签 统计

multithreading ×2

python ×2

exit ×1

websocket ×1