小编jua*_*car的帖子

如何在几秒钟后停止 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”后保持连接,如何强制关闭连接?

非常感谢您的帮助。

python websocket

2
推荐指数
1
解决办法
3658
查看次数

标签 统计

python ×1

websocket ×1