python 3.6 socket pickle数据被截断 [英] python 3.6 socket pickle data was truncated

查看:1011
本文介绍了python 3.6 socket pickle数据被截断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在套接字中发送numpy数组,我使用了pickle,但由于以下错误,我的客户pickle崩溃了:pickle数据被截断了

i can not send my numpy array in socket, i use pickle but il my client pickle crash with this error: pickle data was truncated

我的服务器: 我创建了numpy数组,我想用咸菜发送我的客户端(正在工作)

my server : i create numpy array and i want to send in my client with pickle (it's work)

import socket, pickle
import numpy as np
from PIL import ImageGrab
import cv2


while(True):
    HOST = 'localhost'
    PORT = 50007
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    print ('Connected by', addr)

    arr = np.array([[0, 1], [2, 3]])
    printscreen_pil=ImageGrab.grab(bbox=(10,10,500,500))
    img = np.array(printscreen_pil) ## Transform to Array

    data_string = pickle.dumps(img)
    conn.send(data_string)

    msg_recu = conn.recv(4096)
    print(msg_recu.decode())

    conn.close()

我的客户 他有我的numpy数组,但是我无法加载pickle,我有此错误.

my client He have my numpy array, but i can not load with pickle, i have this error.

import socket, pickle
import numpy as np

HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

msg_a_envoyer = "hello".encode()
s.send(msg_a_envoyer)


while 1:
    data = s.recv(4096)
    if not data: break
    data_arr = pickle.loads(data)
    print (data_arr)
s.close()

推荐答案

问题是,如果腌制数据的大小> 4096,您只会得到腌制数据的第一部分(因此,pickle data was truncated消息是重新获得)

the problem is that if the size of the pickled data is > 4096 you only get the first part of the pickled data (hence the pickle data was truncated message you're getting)

仅当接收完成后,您才需要追加数据并对其进行酸洗,例如:

You have to append the data and pickle it only when the reception is complete, for example like this:

data = b""
while True:
    packet = s.recv(4096)
    if not packet: break
    data += packet

data_arr = pickle.loads(data)
print (data_arr)
s.close()

增加一个字节对象不是很有效,最好将部分存储在对象列表中,然后是join.更快的变体:

increasing a bytes object is not very performant, would be better to store the parts in a list of objects, then join, though. Faster variant:

data = []
while True:
    packet = s.recv(4096)
    if not packet: break
    data.append(packet)
data_arr = pickle.loads(b"".join(data))
print (data_arr)
s.close()

这篇关于python 3.6 socket pickle数据被截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆