如何在几秒钟后停止python websocket连接



我正在尝试开发一个简短的脚本,该脚本通过websocket API连接到实时股票数据提供商,获取一些数据,进行一些计算,将结果存储在数据库中并停止。

编辑:我需要保持连接几秒钟,直到我得到所有需要的数据。因此,在第一条消息之后断开连接不是一种选择。

我面临的问题是如何停止run_forever()连接。

这就是我目前所拥有的:

import websocket
import json
def on_open(ws):
channel_data = {
"action": "subscribe",
"symbols": "ETH-USD,BTC-USD"
}
ws.send(json.dumps(channel_data))

def on_message(ws, message):
# Do some stuff (store messages for a few seconds)
print(message)

def on_close(ws):
print("Close connection")

socket = "wss://ws.url"
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)
ws.run_forever()
ws.close()
# Once the connection is closed, continue with the program

我不想在";做一些事情"执行时,如何强制关闭连接?

非常感谢你的帮助。

我设法解决了这个问题。我留下我的解决方案,以防对某人有用。

我只是向ws对象添加了一些属性,使我能够跟踪接收到的消息数量,并将它们存储在一个列表中,以便在连接关闭后使用。

import websocket
import json
def on_open(ws):
channel_data = {
"action": "subscribe",
"symbols": "ETH-USD,BTC-USD"
}
ws.send(json.dumps(channel_data))

def on_message(ws, message):

ws.messages_count+=1
ws.messages_storage.append(message)

if ws.messages_count>50:
ws.close()

def on_close(ws):
print("Close connection")

socket = "wss://ws.url"
ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message)
# Create a counter and an empty list to store messages
ws.messages_count = 0
ws.messages_storage = []
# Run connection
ws.run_forever()
# Close connection
ws.close()
# Continue with the program

最新更新