server.py
# -*- coding: utf-8 -*-
import ctypes
import socket
import json
# ipv4 SOCK_DGRAM指定了这个Socket的类型是UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# 绑定 客户端口和地址:
s.bind(('', 10182)
print 'Bind UDP on 10182...'
while True:
# 接收数据 自动阻塞 等待客户端请求:
data, addr = s.recvfrom(1024)
message = 'Received from %s:%s.' % (addr, data)
print message
rData = {"message":message}
jsonData = json.dumps(rData)
s.sendto(jsonData.encode("utf-8"),addr)
client.py
# -*- coding: utf-8 -*-
import socket
import json
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
PORT = 10182
network = '<broadcast>'
data = {"cmd":"device report"}
jsonData = json.dumps(data)
# 发送数据:
s.sendto(jsonData.encode("utf-8"), (network, PORT))
while True:
data, addr = s.recvfrom(1024)
message = 'Received from %s:%s.' % (addr, data)
print message