这是我目前正在使用的代码。但我希望它能够使用pickle发送序列化数据。我一直在修补它几个小时而没有运气。也许如果这里的某个人有更好的网络体验,那么快速的洞察力将会受到赞赏,因此我不必重写所有内容,我认为它已经令人困惑。
import select
def send(sdef, data, slen):
sdef.setblocking(0)
sdef.sendall(str(len(str(data))).encode("utf-8").zfill(slen))
sdef.sendall(str(data).encode("utf-8"))
def receive(sdef, slen):
sdef.setblocking(0)
ready = select.select([sdef], [], [], 60)
if ready[0]:
data = int(sdef.recv(slen)) # receive length
# print "To receive: "+str(data)
else:
raise RuntimeError("Socket timeout")
chunks = []
bytes_recd = 0
while bytes_recd < data:
ready = select.select([sdef], [], [], 60)
if ready[0]:
chunk = sdef.recv(min(data - bytes_recd, 2048))
if chunk == b'':
raise RuntimeError("Socket connection broken")
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
else:
raise RuntimeError("Socket timeout")
segments = b''.join(chunks).decode("utf-8")
# print "Received segments: "+str(segments)
return segments
最简单的实施:
import select, pickle
def send(sdef, data, slen):
sdef.setblocking(0)
sdef.sendall(str(len(str(pickle.dumps(data)))).encode("utf-8").zfill(slen))
sdef.sendall(str(pickle.dumps(data)).encode("utf-8"))
def receive(sdef, slen):
sdef.setblocking(0)
ready = select.select([sdef], [], [], 60)
if ready[0]:
data = int(sdef.recv(slen)) # receive length
# print "To receive: "+str(data)
else:
raise RuntimeError("Socket timeout")
chunks = []
bytes_recd = 0
while bytes_recd < data:
ready = select.select([sdef], [], [], 60)
if ready[0]:
chunk = sdef.recv(min(data - bytes_recd, 2048))
if chunk == b'':
raise RuntimeError("Socket connection broken")
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
else:
raise RuntimeError("Socket timeout")
segments = b''.join(chunks).decode("utf-8")
# print "Received segments: "+str(segments)
return segments
我无法反序列化&#34;细分&#34;不再,因为它是一个字符串
答案 0 :(得分:1)
这是获得它的方法,literaleval应该在所有情况下都可以在序列化数据上使用
pickle.loads(ast.literal_eval(segments))