如何在几秒钟后停止 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
我不想在执行“做一些事情”后保持连接,如何强制连接关闭?
非常感谢您的帮助。
I am trying to develop a short script that connects to a real-time stock data provider through a websocket API, gets some data, makes some calculations, stores the results in a database and stops.
EDIT: I need to keep the connection alive for a few seconds until I get all required data. Thus, breaking the connection after the first message is not an option.
The problem I am facing is how to stop the run_forever()
connection.
This is what I have so far:
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
I do not want to stay connected after the "Do some stuff" is executed, how can I force the connection close?
Your help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我设法解决这个问题。我留下我的解决方案以防它对某人有用。
我刚刚向
ws
对象添加了一些属性,这些属性使我能够跟踪收到的消息数量,并将它们存储到一个列表中,以便在连接关闭后使用。I managed how to solve this. I leave my solution in case it is useful to someone.
I just added some attributes to the
ws
object that allows me to track the number of messages received and store them into a list to work with once the connection is closed.