0

我有这个生成字节的python代码

import threading
import socket
import struct
import time
from datetime import datetime
import random

TICKERS = ["AAPL", "GOOG", "MSFT", "SPY"]

timestamp = datetime.utcnow()
ticker = random.choice(TICKERS)
price = 90 + random.randrange(0, 400) * 0.05
size = random.randrange(100, 10000, 100)
msg = struct.pack("!QH%dsdI" % len(ticker), timestamp_millis(timestamp), len(ticker), ticker.encode("ascii"), price, size)
msg_len = struct.pack("!H", len(msg))
print("[%s:%d] %s: %s %.2f %d" % (host, port, timestamp, ticker, price, size))
client_socket.send(msg_len + msg)

我正在使用 akka io 侦听生成此数据的端口。我得到这样的数据:

client received some data: ByteString(0, 26, 0, 0, 1, 90, -30, -44, -92, 21, 0, 4, 71, 79, 79, 71, 64, 88, -106, 102, 102, 102, 102, 102, 0, 0, 10, -116)
client received some data: ByteString(0, 26, 0, 0, 1, 90, -30, -44, -86, -75, 0, 4, 77, 83, 70, 84, 64, 88, -26, 102, 102, 102, 102, 102, 0, 0, 8, -104)
client received some data: ByteString(0, 26, 0, 0, 1, 90, -30, -44, -79, -59, 0, 4, 71, 79, 79, 71, 64, 87, 86, 102, 102, 102, 102, 102, 0, 0, 33, -4)
client received some data: ByteString(0, 25, 0, 0, 1, 90, -30, -44, -69, -126, 0, 3, 83, 80, 89, 64, 88, -29, 51, 51, 51, 51, 51, 0, 0, 0, -56)

我有几个问题: 1. 如何将这些字节解码为普通字符?我尝试:

scala> val bs = ByteString(0, 26, 0, 0, 1, 90, -30, -43, 2, -70, 0, 4, 65, 65, 80, 76, 64, 88, -48, 0, 0, 0, 0, 0, 0, 0, 26, 44)
bs: akka.util.ByteString = ByteString(0, 26, 0, 0, 1, 90, -30, -43, 2, -70, 0, 4, 65, 65, 80, 76, 64, 88, -48, 0, 0, 0, 0, 0, 0, 0, 26, 44)
scala> bs.utf8String
res3: String = ?????Z��?�??AAPL@X�????????,

2. !QH%dsdI 是什么?struct.pack 是如何工作的?我不知道蟒蛇

4

1 回答 1

0

您可以像这样使用名为decodeString的方法:

scala> val bs = ByteString(0, 26, 0, 0, 1, 90, -30, -43, 2, -70, 0, 4, 65, 65, 80, 76, 64, 88, -48, 0, 0, 0, 0, 0, 0, 0, 26, 44)
bs: akka.util.ByteString = ByteString(0, 26, 0, 0, 1, 90, -30, -43, 2, -70, 0, 4, 65, 65, 80, 76, 64, 88, -48, 0, 0, 0, 0, 0, 0, 0, 26, 44)

scala> bs.decodeString("US-ASCII")

!QH%dsdI是一个格式字符串,它由格式字符组成,它指定了被打包/解包的数据类型。

您可以参考此链接以供参考struct.pack

请注意,参数必须与格式要求的值完全匹配。

于 2017-03-19T21:56:22.103 回答