如何 运行 多个 websocket API 并发调用?

How to run multiple websocket API calls concurrently?

在下面的代码中,我对两个不同的 API 进行了两次调用。但是,我不想 运行 一个接一个地调用它们,而是希望同时 运行 它们。我知道可能有不同的方法可以做到这一点,我想知道是否有首选方法?

import asyncio
import websockets
import json

omsg = {"op": "subscribe", "args": [{"channel": "instruments", "instType": "FUTURES"}]}

dmsg = {"jsonrpc": "2.0", "method": "public/get_index_price", "id": 1, "params": {"index_name": "btc_usd"}}

async def call_oapi(omsg):
    async with websockets.connect('wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999') as websocket:
        await websocket.send(omsg)
        response1 = await websocket.recv()
        response2 = await websocket.recv()
        print(response1)
        print(response2)

async def call_dapi(dmsg):
    async with websockets.connect('wss://test.deribit.com/ws/api/v2') as websocket:
        await websocket.send(dmsg)
        response = await websocket.recv()
        print(response)
        
def run(call_api, msg):
    asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))

run(call_dapi, dmsg)
run(call_oapi, omsg)

而不是

def run(call_api, msg):
    asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))

run(call_dapi, dmsg)
run(call_oapi, omsg)

使用

async def main():
    await asyncio.create_task(call_dapi(json.dumps(dmsg)))
    await asyncio.create_task(call_oapi(json.dumps(omsg)))

asyncio.run(main())

你可以用 asyncio.gather 做一些类似的事情,但它是不一样的。我想你想要上面的代码。