rad*_*dar 3 python multithreading websocket
我正在尝试在 python 中实现一个 REST 客户端,该客户端对通过相关服务器打开的 websocket 接收到的服务器收到的消息做出反应。这是场景:
我当前的客户端能够打开 websocket 并接收来自服务器的消息。但是,一旦它收到消息,它就会从服务器获取信息,然后终止,而我想让它继续侦听其他消息,这将使其从服务器获取新内容。
这是我的代码:
def openWs(serverIp, serverPort):
##ws url setting
wsUrl = "ws://"+serverIp+":"+serverPort+"/websocket"
##open ws
ws = create_connection(wsUrl)
##send user id
print "Sending User ID..."
ws.send("user_1")
print "Sent"
##receiving data on ws
print "Receiving..."
result = ws.recv()
##getting new content
getUrl = "http://"+serverIp+":"+serverPort+"/"+result+"/entries"
getRest(getUrl)
Run Code Online (Sandbox Code Playgroud)
我不知道使用线程是否合适,我不是这方面的专家。如果有人能提供帮助,那就太好了。
提前致谢。
我完成了这段代码,做了我所期望的事情。从这里获取它
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):
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__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:5000/chat",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10941 次 |
| 最近记录: |