如何使用Websocket向服务器发送消息

时间:2019-02-15 03:46:39

标签: python websocket python-asyncio

我正在尝试向服务器发送消息以获取答案。

我尝试使用该站点上的官方websocket API,但我不理解它们或无法使其按需运行,因此我正在尝试构建它。

import asyncio
import websockets

 async def test():

     async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:

        await websocket.send("ping")
  #OR   await websocket.send({"op": "subscribe", "args": [<SubscriptionTopic>]})

        response = await websocket.recv()
        print(response)

 asyncio.get_event_loop().run_until_complete(test())

我已经连接了,但是我没有收到“ pong”作为对“ ping”的回答,也没有收到“好,您已订阅此主题”,因为在回显网站上尝试执行命令时,我没有得到接收。 / p>

#!/usr/bin/env python3

import asyncio
import websockets
import json

var = []

async def test():
async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:
    response = await websocket.recv()
    print(response)


    await websocket.send(json.dumps({"op": "subscribe", "args": "trade:TRXH19"}))
    response = await websocket.recv()

    resp = await websocket.recv()
    print(json.loads(resp))

    sum=0

    while True:

        resp = await websocket.recv()
        jj = json.loads(resp)["data"][0]
        var.append(jj)
        size = jj["size"]
        side = jj["side"]
        coin = jj["symbol"]
        if side=="Buy":
            sum+=size
        else:
            sum-=size
        print(coin)
        print(size)
        print(side)
        print("Totale = ", sum )

while True:
    asyncio.get_event_loop().run_until_complete(test())
    print(var)
    print("Ciclo Finito!!!!")

1 个答案:

答案 0 :(得分:4)

那是因为您必须在每次发送后读取接收到的数据。

#!/usr/bin/env python3

import asyncio
import websockets
import json

var = []

async def test():
    async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:
        response = await websocket.recv()
        print(response)

        await websocket.send("ping")
        response = await websocket.recv()
        print(response)
        var.append(response)

        await websocket.send(json.dumps({"op": "subscribe", "args": "test"}))
        response = await websocket.recv()
        print(response)

asyncio.get_event_loop().run_until_complete(test())

print(var)

输出:

{"info":"Welcome to the BitMEX Realtime API.","version":"2019-02-12T19:21:05.000Z","timestamp":"2019-02-17T14:38:32.696Z","docs":"https://www.bitmex.com/app/wsAPI","limit":{"remaining":37}}
pong
{"status":400,"error":"Unknown table: test","meta":{},"request":{"op":"subscribe","args":"test"}}
['pong']

编辑-处理websockets下降和多个数据的代码:

#!/usr/bin/env python3

import asyncio
import websockets
import json

total = 0

async def test():
    async with websockets.connect('wss://www.bitmex.com/realtime') as websocket:
        response = await websocket.recv()
        print(response)


        await websocket.send(json.dumps({"op": "subscribe", "args": "trade:TRXH19"}))
        response = await websocket.recv()

        #resp = await websocket.recv()
        #print(json.loads(resp))

        global total

        while True:
            resp = await websocket.recv()
            print(resp)
            for jj in json.loads(resp)["data"]:
                size = jj["size"]
                side = jj["side"]
                coin = jj["symbol"]

                if side == "Buy":
                    total += size
                else:
                    total -= size
                print(coin)
                print(size)
                print(side)
                print("Totale = ", total)



while True:
    loop = asyncio.new_event_loop()
    try:
        loop.run_until_complete(test())
    except Exception as e:
        print(e)
        loop.close()
    #finally:


    print(total)
    print("Ciclo Finito!!!!")