【发布时间】:2014-07-15 14:38:29
【问题描述】:
在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'
【问题讨论】:
-
把它序列化成 JSON 怎么样? docs.python.org/2/library/json.html 是否足以满足您的需求,还是您需要传输的不仅仅是列表、字典、字符串、True/False/None 和 ints/floats?
-
这似乎不起作用。我尝试了
sock.sendall(json.dumps(data)),数据为dict,但出现错误TypeError: 'str' does not support the buffer interface。 -
关于
TypeError,请参阅stackoverflow.com/questions/5471158/… -
@dano:嗯,因为那个错误,我首先发布了我的问题。由于错误
AttributeError: 'str' object has no attribute 'decode',您发布的链接中的解决方案也不起作用。
标签: python sockets python-3.x dictionary