我想從下面的代碼中讀取UDP廣播響應。找到兩臺服務器併爲這兩臺服務器返回信息。我想要做的是爲每個回覆制定一個詞典,但我似乎無法區分個別回覆。任何人都可以提出一些建議嗎?如何閱讀來自UDP廣播的JSON響應
import socket
import json
socket.setdefaulttimeout(.5)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
s.sendto("D", ('255.255.255.255', 30303))
while True:
response = s.recv(2048)
response = json.loads(response)
print response
這是響應:用您的建議,如果我正確地做這件事,讓我ValueErrors
{u'Product': u'OWServer_v2-Enet', u'Name': u'OWServer_v2-Enet_19', u'IP': u'10.0.1.19', u'TCPIntfPort': u'0', u'HTTPPort': u'80', u'MAC': u'00-04-A3-B1-F1-86', u'Bootloader': u'POST', u'FWVer': u'1.44', u'NETBios': u'EDSOWSERVER19 '}
{u'Product': u'OWServer_v2-Enet', u'Name': u'OWServer_v2-Enet_20', u'IP': u'10.0.1.20', u'TCPIntfPort': u'0', u'HTTPPort': u'80', u'MAC': u'00-04-A3-C1-43-86', u'Bootloader': u'POST', u'FWVer': u'1.44', u'NETBios': u'EDSOWSERVER20 '}
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
socket.timeout: timed out
。
buf = ""
while True:
buf = buf + s.recv(2048)
resp = ''
if "\n" in buf:
resp, buf = buf.split("\n", 1)
if resp:
print json.loads(resp)
raise ValueError(errmsg("Expecting property name", s, end - 1))
ValueError: Expecting property name: line 1 column 32 (char 32)
你試過[迭代](http://stackoverflow.com/questions/1078118/how-do-i-iterate-over-a-json-structure)?當我不確定你嘗試過什麼時,很難變得更有幫助。 –