1、发送
def send_data(s, ):
while True:
# print('开启发送数据线程--------')
s.sendto('STATE_CODE_ML:0:机器学习模块正常运行中'.encode('utf-8'), ('127.0.0.1', 8002))
time.sleep(1)
2、接收
def recv_data(s, ):
while True:
# print('开启接收数据线程--------')
data = s.recvfrom(1024)
print('{} {}'.format(data[0].decode('utf-8'), data[1]))
注意recvfrom,如果没有收到函数会阻塞;
1024不是端口而是接收1024个字节大小【这个和其他语言不一样】
3、调用
if __name__ == "__main__":
cfg = get_config()
address_rcv = (cfg.get('General', 'UDP_IP'), int(cfg.get('General', 'UDP_RCV_PORT')))
udp_rcv = socket(AF_INET, SOCK_DGRAM)
udp_rcv.bind(address_rcv)
thread_recv = threading.Thread(target=recv_data, args=(udp_rcv,))
thread_recv.start()
address_send = (cfg.get('General', 'UDP_IP'), int(cfg.get('General', 'UDP_SEND_PORT')))
udp_send = socket(AF_INET, SOCK_DGRAM)
udp_send.bind(address_send)
thread_send = threading.Thread(target=send_data, args=(udp_send,))
thread_send.start()
heart_beat(udp_send)
注意参数需要是元组格式的,所以要加个逗号;
由于接收函数可能会阻塞,所以如果需要循环发送数据,就不能使用同一个socket,我这里便是用了两个端口对应两个socket