python - Python `websockets` 库服务器不流式传输任何数据,但连接并首先发送/接收正常
问题描述
我正在尝试获取 Polygon.io 报价数据的简单随机价格模拟器,用于在市场关闭时测试随机信号上的简单技术指标。由于周末市场现在关闭,polygon.io 不会返回价格,这显然是正确的。所以我只想要一个 100 行的websockets
库服务器模拟器。但它不起作用。
服务器代码:
import asyncio, websockets, time, json
CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(4)
state = CONNECTING
timestamp = 0
async def polygon_io_simulator(websocket, path):
global state, timestamp
while True:
if state == STREAMING:
ask_price = 0.0
bid_price = 1.0
response = [{
"t": timestamp,
"a": ask_price,
"b": bid_price,
}]
#await websocket.recv()
await websocket.send(json.dumps(response))
timestamp += 1
elif state == CONNECTING:
await websocket.send("Connected Successfully")
state = AUTHENTICATING
elif state == AUTHENTICATING:
await websocket.recv()
await websocket.send('authenticated')
state = SUBSCRIBING
elif state == SUBSCRIBING:
data = await websocket.recv()
print(data)
await websocket.send('subscribed')
state = STREAMING
#time.sleep(0.05)
start_server = websockets.serve(polygon_io_simulator, "localhost", 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
客户代码:
import websocket
#websocket.enableTrace(True)
import os, json, sys
from datetime import datetime
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication
API_KEY = os.environ['POLYGON_IO_APIKEY']
FOREX_ASSET = 'EUR/USD'
WEBSOCKET_URL = 'ws://localhost:8000' # wss://socket.polygon.io/forex
START, CONNECTING, AUTHENTICATING, SUBSCRIBING, STREAMING = range(5)
state = START
def on_message(ws, msg):
global state, curve, data_x, data_y, widget
if state == STREAMING:
# Realtime data plot. Each time this function is called, the data display is updated
json_data = json.loads(msg)[0]
mid_price = (json_data['a'] + json_data['b'])/2.0
print(mid_price)
elif state == CONNECTING:
if 'Connected Successfully' in msg:
state = AUTHENTICATING
ws.send(f'{{"action":"auth","params":"{API_KEY}"}}')
print('Authenticating....')
else:
print("FAILED TO CONNECT")
elif state == AUTHENTICATING:
if "authenticated" in msg:
state = SUBSCRIBING
ws.send(f'{{"action":"subscribe","params":"C.{FOREX_ASSET}"}}')
print(f'Subscribing to {FOREX_ASSET} ....')
else:
print("FAILED TO AUTHENTICATE")
elif state == SUBSCRIBING:
if "subscribed" in msg:
state = STREAMING
print('Streaming data ....')
else:
print("FAILED TO SUBSCRIBE")
def on_error(ws, err):
print(err)
def on_open(ws):
print('WebSocket connection opened.')
def on_close(ws):
print('WebSocket connection closed.')
state = CONNECTING
class WebSocketThread(QThread):
def __init__(self):
super().__init__()
self._ws = websocket.WebSocketApp(
WEBSOCKET_URL,
on_close=on_close,
on_message=on_message,
on_error=on_error,
on_open=on_open)
def run(self):
self._ws.run_forever()
if __name__ == '__main__':
app = QApplication([])
thread = WebSocketThread()
thread.start()
sys.exit(app.exec_())
客户端打印:
WebSocket connection opened.
Authenticating....
Subscribing to EUR/USD ....
Streaming data ....
很明显,WebSockets 在双方都有效。我的调试器说服务器反复进入 STREAMING send() 行,但是,我的客户端在on_message
例程中没有收到任何内容。
这很奇怪……
解决方案
推荐阅读
- angular - 如何克隆组件?
- github - 使用 github.com GUI
- sql-server - 在 SQL 中格式化十进制数
- linker - 每次编译程序时,头文件都会执行吗?
- ruby-on-rails - 如何将值从视图发送到控制器
- javascript - 将 2 个大小不等的 JSON 对象与 ID 组合在一起
- arrays - 打印来自 For Each 函数 VBA 的数组结果得到下标超出范围错误
- c++ - 独立 SDL 的局限性是什么?为什么人们选择使用 openGL 上下文?
- azure - 如何更新 Azure DeviceTwin NESTED 所需的属性?(爪哇)
- javascript - SVG 路径动画运行非常缓慢,落后于我在 Chrome 中的其他选项卡