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

jua*_*car 2 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
Run Code Online (Sandbox Code Playgroud)

我不想在执行“Do some stuff”后保持连接,如何强制关闭连接?

非常感谢您的帮助。

jua*_*car 6

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

我刚刚向该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
Run Code Online (Sandbox Code Playgroud)