python 3.6 socket pickle 数据被截断
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44637809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python 3.6 socket pickle data was truncated
提问by sazearte
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)
我的服务器:我创建了 numpy 数组,我想用泡菜发送我的客户端(它的工作)
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()
my client He have my numpy array, but i can not load with pickle, i have this error.
我的客户他有我的 numpy 数组,但我无法加载泡菜,我有这个错误。
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()
采纳答案by Jean-Fran?ois Fabre
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)
问题是,如果腌制数据的大小 > 4096,您只能获得腌制数据的第一部分(因此pickle data was truncated
您得到的消息)
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()
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:
增加一个字节对象的性能不是很好,最好将这些部分存储在对象列表中,然后join
,不过。更快的变体:
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()