【发布时间】:2019-08-26 12:19:14
【问题描述】:
我使用 python 从 nodejs 服务器接收流数据,使用以下 python 代码。 websocket 假设获取实时流数据。我假设 python 的 WebSocketApp 获取流数据的唯一方法是通过 on_message()。
但是,尽管可以成功建立连接,但永远不会调用 on_message()。 on_open() 仍然被调用,并且 ping 消息已定期发送到服务器以维持心跳。
我在互联网上进行了搜索,但找不到导致 on_message() 失败的线索?
我在本地和远程测试了连接,连接良好。
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()
相信在成功检索后,信息将以json格式传回。
【问题讨论】:
-
你能至少显示堆栈跟踪或解释器在运行此代码时抛出的错误吗?
-
你能链接你正在使用的 websocket 库吗?
-
@Mobrine Hayde,没有错误。有一个日志说建立了连接,最远的是执行
print('receiving message...'),然后连接保持打开但没有任何反应。 -
@Tim Woocker,python 使用
websocket,nodejs 也使用websocket