【问题标题】:How to send the content of a dictionary properly over sockets in python3x?如何通过python3x中的套接字正确发送字典的内容?
【发布时间】: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


【解决方案1】:

这主要是对 cme​​ts 的总结,但是您需要将 dict 转换为 json str 对象,将 str 对象通过编码转换为 bytes 对象,然后通过套接字发送。在服务器端,您需要将通过套接字发送的bytes 对象解码回str,然后使用json.loads 将其转回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)

【讨论】:

  • @Alex,这是一个单独的问题。我将扩展我的服务器端示例代码,这可能会揭示您的错误。我的猜测是您使用原始的 socket 对象来调用 recv 而不是 sock.accept 返回的对象。
  • @Alex,如果您知道您发送的 dict 的大小会有一些限制,您可以使缓冲区更大。否则,就像您说的那样,您在 while 循环中执行 recv。 socket 的 Python 文档显示了这一点:docs.python.org/2/library/socket.html#example
  • 您发布的链接没有显示从recv 读取数据并将它们“添加”在一起的示例。如果数据 rom recv 只是文本(如在 python 2.x 中),这很容易,因为您初始化了一个空字符串。但是对于python 3.x,您需要初始化一个空字节对象或其他东西......
  • @Alex,对。幸运的是,制作一个空的byte 很容易。查看我的编辑。
  • 完美!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 2023-03-05
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多