Python中的 list 或者 dict 都可以转成JSON字符串来发送,接收后再转回来。
首先
import json
然后,把 list 或 dict 转成 JSON
json_string = json.dumps(list_or_dict)
如果你用的是Python3,这里的 json_string 会是 str 类型(即Python2的unicode类型),可能需要编码一下:
if type(json_string) == six.text_type:
json_string = json_string.encode('UTF-8')
用socket发送过去,例如
s.sendto(json_string, address)
对方用socket接收,例如
json_string, addr = s.recvfrom(2048)
把JSON转成 list 或 dict
list_or_dict = json.loads(json_string)
下面是个完整的例子:
client.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import socket
import json
import six
address = ('127.0.0.1', 31500)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
json_string = json.dumps(mylist)
if type(json_string) == six.text_type:
json_string = json_string.encode('UTF-8')
s.sendto(json_string, address)
s.close()
server.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import socket
import json
address = ('127.0.0.1', 31500)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(address)
json_string, addr = s.recvfrom(2048)
mylist = json.loads(json_string)
print(mylist)
s.close()
请先运行server.py,再运行client.py
UDP不适合传输很大的数据包。