[英]Unpacking objects individually from a TCP stream
我想一一閱讀來自 TCP stream 的對象,最好使用MessagePack庫。
一方面,我有一個客戶端,在循環的每次迭代中:
另一方面,服務器:
現在我在接收時將數據存儲在緩沖區中,然后在 stream 結束時繼續解包。 我的問題是我需要在發送元組時一一解包。 換句話說,我想實時讀取數據而不將其放入緩沖區。
如果有可能,我如何使用 MessagePack 實現這一點?
- 客戶端 -
#Python3.7
import socket
import msgpack
import math
HOST = "127.0.0.1"
PORT = 9000
den = 40
rad = 100
theta = math.tau / den
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT)) #connect to server
for step in range(den):
x = math.cos(i*theta) * rad
y = math.sin(i*theta) * rad
data = msgpack.packb((x, y), use_bin_type = True)
sock.sendall(data)
- 服務器端 -
#Jython2.7 <-- Python 2.7 compatible only
from io import BytesIO
import msgpack
import socket
HOST = "127.0.0.1"
PORT = 9000
buf = BytesIO()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
connection, address = s.accept()
while True:
try:
data = connection.recv(1024)
buf.write(data)
except:
buf.seek(0)
unpacker = msgpack.Unpacker(buf, use_list=False, raw=False)
for unpacked in unpacker:
print(unpacked)
buf = BytesIO()
請參閱自述文件中的“流解包”部分: https://github.com/msgpack/msgpack-python#streaming-unpacking
你可以這樣做:
unpacker = msgpack.Unpacker(use_list=False, raw=False)
while True:
data = connection.recv(1024)
if not data:
break
unpacker.feed(data)
for unpacked in unpacker:
print(unpacked)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.