# coding=utf-8
import websocket,threading,json,time
websocket_url = "wss://test-im.y.com/?platform=3&token=54348d&bizType=3&sessionId=2a"
ws_msg = ""
def on_message(ws, message):
# print(message) #接收的消息体
global ws_msg #引用全局变量ws_msg
if json.loads(message)['data']['action'] == 'end':
print('==========流式消息接收完毕,断开ws连接!!!==========')
ws.close()
else:
msg = json.loads(message)['data']['content']
print(f'{int(time.time() * 1000)}接收到的消息:{msg}') #流式消息段(并记录收到该段消息的时间戳)
ws_msg = ws_msg + msg #拼接流式消息
ws = websocket.WebSocketApp(websocket_url,on_message=on_message)
def run_websocket():
ws.run_forever() #运行WebSocket连接,启动一个无限循环(ws断开后继续往下执行该函数)
print(f'完整消息体:{ws_msg}')
websocket_thread = threading.Thread(target=run_websocket)
websocket_thread.start() #后台开始一个新线程接收消息,脚本当前线程继续执行
print('此处可续写一个消息发送,根据后台线程的消息接收,记录问答内容以及message响应时间')
python脚本-后台新线程持续接收websocket流式消息
最新推荐文章于 2024-06-24 11:55:11 发布