您的代码的问题在于,当在TCP套接字上使用recv(4096)时,由于它们在数据包边界处进行了切片,因此返回的数据量可能与预期的不同.
一种简单的解决方案是为每个消息添加长度.用于发送像
import struct
packet = pickle.dumps(foo)
length = struct.pack('!I', len(packet)
packet = length + packet
然后接收
import struct
buf = b''
while len(buf) < 4:
buf += socket.recv(4 - len(buf))
length = struct.unpack('!I', buf)[0]
# now recv until at least length bytes are received,
# then slice length first bytes and decode.
但是,Python标准库已经支持面向消息的腌制套接字,即multiprocessing.Connection,该套接字分别使用Connection.send和Connection.recv轻松支持发送和接收腌制.
因此,您可以将服务器编码为
from multiprocessing.connection import Listener
PORT = 1234
server_sock = Listener(('localhost', PORT))
conn = server_sock.accept()
unpickled_data = conn.recv()
和客户作为
from multiprocessing.connection import Client
client = Client(('localhost', 1234))
client.send(['hello', 'world'])