[英]python websocketapp on_message() method not working
I use python to receive streaming data from nodejs server, with the following python code.我使用 python 从 nodejs 服务器接收流数据,使用以下 python 代码。 The websocket suppose to get real time streaming data.
websocket 假设获取实时流数据。 And I assume the only way for python's WebSocketApp to get the streaming data is via on_message().
我假设 python 的 WebSocketApp 获取流数据的唯一方法是通过 on_message()。
However, despite connection can be successfully established, the on_message() is never called.然而,尽管可以成功建立连接,但永远不会调用 on_message()。 on_open() still called, and ping message has been routinely sent to the server to maintain the heartbeat.
on_open() 仍然被调用,并且 ping 消息已定期发送到服务器以保持心跳。
I searched through the internet and cannot find a clue as of what's happening that makes on_message() failures?我在互联网上搜索并找不到导致 on_message() 失败的原因的线索?
I tested the connection locally and remotely, connection is good.我在本地和远程测试了连接,连接良好。
import websocket
from websocket import create_connection
import json
try:
import thread
except ImportError:
import _thread as thread
import time
def on_message(ws, message):
print('on msg called')
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
time.sleep(1)
ws.close()
print("### closed ###")
def on_open(ws):
def run(*args):
time.sleep(1)
print('sending from run()...')
ws.send("{\"login\":\"login\",\"password\":\"pw\"}")
time.sleep(1)
try:
print('receiving message...')
#result = json.loads(ws.receive())
#result = ws.recv_frame()
#result = json.loads(ws.recv())
#print(result)
except Exception as e:
print('failed to receive messages...')
print(e)
time.sleep(1)
ws.close()
thread.start_new_thread(run, ())
if __name__ == "__main__":
try:
websocket.enableTrace(True) # show the header part
ws = websocket.WebSocketApp("ws://localhost:4010",
subprotocols=["echo-protocol"],
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever(ping_interval=0,ping_timeout=0)
except KeyboardInterrupt:
ws.close()
it is believed that upon successful retrieval, info would be passed back in json format.相信成功检索后,信息将以json格式传回。
It seems that with your code, the on_message inside the class WebsockeApp is called, and not that one you have in your code.似乎在您的代码中,调用了 WebsockeApp 类中的 on_message,而不是您的代码中的那个。 To let run the on_message in your code, just make an own class inside your code and then change in your object creation to
要在代码中运行 on_message,只需在代码中创建一个自己的类,然后将对象创建更改为
From:从:
on_message = on_message
To:到:
ws = websocket.WebSocketApp("ws://localhost:4010", subprotocols=["echo-protocol"], on_message = YourClassName.on_message, on_error = on_error, on_close = on_close)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.