zoukankan      html  css  js  c++  java
  • python 线程+udp

    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

  • 相关阅读:
    sql执行的顺序
    $(obj).index(this) 与 $(this).index()的区别
    java取得百分比
    取得input的特殊值
    清除select的边框和三角形
    在jsp页面中获取列表长度
    mysql mybatis 批量更新和新增
    oracle mybatis 批量更新和新增
    jstl if else 判断
    判断radio,select,checkbox是否选中的方法
  • 原文地址:https://www.cnblogs.com/judes/p/12598549.html
Copyright © 2011-2022 走看看