基于python 版paho.mqtt 和线程池的生产者和消费者模式示例

client.on_message 收到主题消息后就把处理函数扔到线程池里,待线程池有线程空闲时,将启动相关线程。另外,可同时收发(收发异步)。

# encoding=utf8
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import time
import socket
import requests
import threading
from concurrent.futures import ThreadPoolExecutor


# 基于python 语言的paho.mqtt 多线程异步示例
# 2020/07/20
# (2条消息)python线程池及其原理和使用_whatday的专栏-CSDN博客_python 线程池
# https://blog.csdn.net/whatday/article/details/90674449

pool = ThreadPoolExecutor(max_workers=2)

# 定义一个准备作为线程任务的函数
def process_data(msg):
    for i in range(100):
        time.sleep(0.5)
        print("子线程" + str(threading.current_thread().ident) + ", 循环:" + str(i))
        publish.single("donehello", msg.payload, hostname="xxx.xxx.xxx.xxx", port=1883)

def get_host_ip():
    """
    查询本机ip地址
    :return:
    """
    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(('8.8.8.8',80))
        ip=s.getsockname()[0]
    finally:
        s.close()
    return ip


# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    if 0==rc:
        print("连接成功")
    elif 1==rc:
        print("连接失败-不正确的协议版本")
    elif 2==rc:
        print("连接失败-无效的客户端标识符")
    elif 3==rc:
        print("连接失败-服务器不可用")
    elif 4==rc:
        print("连接失败-错误的用户名或密码")
    elif 5==rc:
        print("连接失败-未授权")
    else:
        print("6-255: 未定义.")

    print(get_host_ip()) # 获取本机的内网ip
    print(requests.get('http://ifconfig.me/ip', timeout=1).text.strip()) #获取本机的外网ip
    client.subscribe("demo")# 订阅主题为 /geometricCorrection/本机ip

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    pool.submit(process_data, msg)
    client.publish("done", "done")


client = mqtt.Client("feizusemqtt"+ get_host_ip())
client.on_connect = on_connect
client.on_message = on_message

client.connect("xxx.xxx.xxx.xxx", 1883, 60)
client.loop_forever()
# loop_forever()之后的语句不会执行

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值