如何在Python3x中通过套接字正确发送字典内容?
在使用 python3.x
的套接字时,我想通过套接字发送一个字典的内容,但由于某些原因,上面链接的内容没有回答我的问题...
client.py:
a = {'test':1, 'dict':{1:2, 3:4}, 'list': [42, 16]}
bytes = foo(a)
sock.sendall(bytes)
server.py:
bytes = sock.recv()
a = bar(bytes)
print(a)
我该如何把任何字典转换成字节序列(这样才能通过套接字发送),然后又如何把它转换回来呢?我希望这个过程简单明了。
到目前为止,我尝试过的内容:
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'
1 个回答
12
这段话主要是在总结评论内容。你需要把字典(dict)转换成一个 JSON 格式的字符串(str)对象,然后再把这个字符串对象编码成字节(bytes)对象,最后通过网络连接发送出去。在服务器端,你需要把接收到的字节对象解码回字符串,然后使用 json.loads
方法把它转换回字典。
客户端:
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)