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()之后的语句不会执行