1 udp 广播接收程序
struct.unpack 函数默认解析的网络字节序数据
import io
from socket import *
import sys
import time
import struct
udp_buf_len=128
UDP_PORT=10000
def bytes2float(byte_data):
return struct.unpack("!f",byte_data)[0]
def udp_broacast_init():
s = socket(AF_INET, SOCK_DGRAM, 0)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('0.0.0.0', UDP_PORT))
print("udp_broacast_init ok.")
return s
def udp_broadcat_recv(s):
while True:
data,addr = s.recvfrom(udp_buf_len)
hvF_b = data[0:4]
apd_b = data[4:8]
temp_b = data[8:12]
mems1_b = data[12:16]
mems2_b = data[16:20]
hvF = bytes2float(hvF_b)
adpF = bytes2float(apd_b)
tempF = bytes2float(temp_b)
memsF1 = bytes2float(mems1_b)
memsF2 = bytes2float(mems2_b)
print("hvF:",hvF," apdF:", adpF, " tempF:", tempF, " memsF1:", memsF1, " memsF2:" , memsF2)
def main():
print("Hello world.")
s = udp_broacast_init()
udp_broadcat_recv(s)
if __name__ == '__main__':
main()
|