python eoferror_python-Pickle EOFError:从套接字接收时跑出输...

您的代码的问题在于,当在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'])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值