先来看一下一个正常的使用示例:
# coding:utf-8
# filename:mqttDemo.py
#------------------Imports-------------------
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
#--------------------------------------------
#----------------全局变量定义----------------
HOST = "localhost"
PORT = 1883
Username = 'username'
Password = 'password'
#--------------------------------------------
# 连接服务器
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(client._topic)
# 发送消息
def send_message(topic, msg):
global HOST, PORT
try:
publish.single(topic, msg, hostname=HOST, port=PORT)
except:
print('[exception]: mqtt message send failed.')
# 回调方法
def on_message_callbak(client, userdata, msg):
try:
msg = msg.payload.decode('utf-8')
print(msg)
except:
print('[exception]: on_message callback exception. [API_mqtt.py -> on_message]')
# 获取client
def get_client(topic, func):
global Username, Password
client = mqtt.Client()
client._topic = topic
client.username_pw_set(Username, Password)
client.on_connect = on_connect
client.on_message = func
return client
# 消息接收
def receive_message(topic, func):
client = get_client(topic, func)
client.connect(HOST, PORT, 60)
client.loop_forever()
if __name__ == '__main__':
receive_message('testTopic', on_message_callback)
简单讲解一下:
<