簡體   English   中英

如何使用Websocket向服務器發送消息

[英]How to send a message to Server with Websocket

我正在嘗試向服務器發送消息以獲得答案。

我試圖使用網站上的官方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”的答案,也沒有收到“你贊成這個主題的好”,因為我在echo網站上嘗試命令時收到了。

#!/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!!!!")

那是因為你必須在每次發送后讀取收到的數據。

#!/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!!!!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM