如何在python3x的套接字上正确发送字典的内容? [英] How to send the content of a dictionary properly over sockets in python3x?
问题描述
在python3.x
中使用套接字,我想通过套接字发送字典的内容,由于某些原因,该行上方的链接无法回答该问题...
Using sockets in python3.x
I want to send the content of a dictionary over a socket, which for some reasons is NOT answered by the link just above this line...
client.py:
client.py:
a = {'test':1, 'dict':{1:2, 3:4}, 'list': [42, 16]}
bytes = foo(a)
sock.sendall(bytes)
server.py:
server.py:
bytes = sock.recv()
a = bar(bytes)
print(a)
如何将任何字典转换为字节序列(可以通过套接字发送)以及如何转换回?我更喜欢一种简洁的方法.
How to convert any dictionary to a sequence of bytes (to be able to be sent through a socket) and how to be converted back? I prefer a clean and simple way to do this.
到目前为止我尝试过的:
What I have tried so far:
sock.sendall(json.dumps(data))
TypeError: 'str' does not support the buffer interface
sock.sendall(bytes(data, 'UTF-8'))
TypeError: encoding or errors without a string argument
data = sock.recv(100)
a= data.decode('UTF-8')
AttributeError: 'str' object has no attribute 'decode'
推荐答案
这主要是对注释进行汇总,但是您需要将dict转换为json str
对象,然后将该str
对象转换为bytes
对象,方法是将其编码,然后通过套接字发送该对象.在服务器端,您需要将通过套接字发送的bytes
对象解码回str
,然后使用json.loads
将其转换回dict
.
This is primarily summarizing the comments, but you need to convert the dict to a json str
object, convert that str
object to a bytes
object by encoding it, and then send that over the socket. On the server-side, you need to decode the bytes
object sent over the socket back to a str
, and then use json.loads
to turn it back into a dict
.
客户:
b = json.dumps(a).encode('utf-8')
s.sendall(b)
服务器:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 1234))
s.listen(1)
conn, addr = s.accept()
b = b''
while 1:
tmp = conn.recv(1024)
b += tmp
d = json.loads(b.decode('utf-8'))
print(d)
这篇关于如何在python3x的套接字上正确发送字典的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!