解压缩websocket数据时出现问题

2024-03-28 21:58:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从Bitmart的WebSocket(交换)中获取数据。我可以订阅WebSocket并取回数据,但它是压缩的,根据Documentation,我应该使用zlib来解压缩数据,但当我尝试这样做时,它给出了一个错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcd in position 1: invalid continuation byte

这是我的代码:

import json
from websocket import create_connection
import zlib

ws = create_connection("wss://ws-manager-compress.bitmart.news?protocol=1.1")
ws.send(json.dumps({
    "op": "subscribe",
    "args": ["spot/ticker:BTC_USDT"]
}))

while True:
    result = ws.recv()
    message = result
    compressed = zlib.compress(message)
    decompressed = zlib.decompress(compressed).decode('UTF-8')
    print(decompressed)

ws.close()

顺便说一句ws.recv()返回如下数据:

b'5\xcd\xd1\x0e\x82 \x18\x05\xe0w\xf9\xaf\x1d\x01\x82\xbfzY\xbdAv\xd5\x1aCc\xe9\xc2pB\xb5\xe6|\xf7`\xcb\xdb\xef\x9c\x9d\xb3\xc0M\x07\r\xf5e\x81V{\xa3\xde\xce\xbeF\xa3\xb8\xe8\xa1\x06N\xab\x1c\x11+\x82\x122\xe8\x87{\xff\x0fdI)%\x94F\xb5\xda\x075\xcdCg\x92#2I\x10\x93\xbb\xcfV\x96L\xe4\xa4,"\xba\xc9<7\xc5\x9cK\xc2\xd2\x84W\x01jVp*\xa8(\xa5\x8c\xf0\x1d[gci\xdf\x1c\xd4\xf9tl`\xbdf\x10tk\xd3\x89\x9f\\\xd8\x85\xa1{\x98\x19\xd6\x1f'

Tags: 数据importjsonmessagewscreateresultbyte