ant*_*tho 9 python websocket python-3.x python-asyncio
I don't understand the difference between websocket (websocket client) and websockets. I would like to understand the difference to know which one uses to be optimal.
I have a code that seems to do the same thing.
import websockets
import asyncio
import json
async def capture_data():
uri = "wss://www.bitmex.com/realtime?subscribe=instrument:XBTUSD"
#uri = "wss://www.bitmex.com/realtime"
async with websockets.connect(uri) as websocket:
while True:
data = await websocket.recv()
data = json.loads(data)
try :
#print('\n', data['data'][0]["lastPrice"])
print('\n', data)
except KeyError:
continue
asyncio.get_event_loop().run_until_complete(capture_data())
Run Code Online (Sandbox Code Playgroud)
import websocket
import json
def on_open(ws):
print("opened")
auth_data = {
'op': 'subscribe',
'args': ['instrument:XBTUSD']
}
ws.send(json.dumps(auth_data))
def on_message(ws, message):
message = json.loads(message)
print(message)
def on_close(ws):
print("closed connection")
socket = "wss://www.bitmex.com/realtime"
ws = websocket.WebSocketApp(socket,
on_open=on_open,
on_message=on_message,
on_close=on_close)
ws.run_forever()
Run Code Online (Sandbox Code Playgroud)
EDIT:
Python 是否足够强大,可以通过 websocket 接收大量数据?在高流量时期,我可以每秒处理数千条消息,甚至在短时间内处理数万条消息。
我已经看到很多关于 Nodejs 的东西可能比 python 更好,但我不知道 js,即使我只是从互联网上复制代码我也不确定如果我必须发送数据到我的python脚本然后处理它。
websocket-client仅实现客户端。如果你想创建一个 WebSocket 服务器,你必须使用websockets.
websocket-client实现了 WebSocketApp,它更像是 JavaScript 的 websocket 实现。
我更喜欢 WebSocketApp 作为线程运行:
socket = "wss://www.bitmex.com/realtime"
ws = websocket.WebSocketApp(socket,
on_open=on_open,
on_message=on_message,
on_close=on_close)
wst = threading.Thread(target=lambda: ws.run_forever())
wst.daemon = True
wst.start()
# your code continues here ...
Run Code Online (Sandbox Code Playgroud)
现在您有了异步 WebSocket。您的大型机程序正在运行,每次收到消息时,on_message都会调用函数。on_message自动处理消息,无需主机中断。
| 归档时间: |
|
| 查看次数: |
1914 次 |
| 最近记录: |