从 TCP 流中单独解包对象

Unpacking objects individually from a TCP stream

我想一个一个地读取来自 TCP 流的对象,最好使用 MessagePack 库。

一方面,我有一个 客户端,在循环的每次迭代中:

另一方面,服务器

现在我在接收时将数据存储在缓冲区中,然后在流结束时继续解包。我的问题是我需要在元组发送时 一个一个地解压它们 。换句话说,我想 实时读取数据 而不是将其放入缓冲区。

如果可能的话,我如何使用 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()

参见自述文件中的 "Stream Unpacking" 部分: 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)