開發環境Pycharm + paho-mqq包。 本示例的mqtt 是阻塞式的。
# encoding=utf8
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import json
# 參考:
# Eclipse Paho - MQTT and MQTT-SN software
# https://www.eclipse.org/paho/clients/python/
# python paho-MQTT_qq_38059635的博客-CSDN博客_python paho mqtt
# https://blog.csdn.net/qq_38059635/article/details/88583800
# 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))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("suanfa/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
print(str(msg.topic))
s = json.loads(msg.payload)
print("type:" + s["type"])
client.publish("test","hello")
def on_message_msgs(mosq, obj, msg):
# This callback will only be called for messages with topics that match
# $SYS/broker/messages/#
print("MESSAGES: " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
client = mqtt.Client("pythonclient")
client.message_callback_add('suanfa/a', on_message_msgs)
client.on_connect = on_connect
client.on_message = on_message
# client.connect("mqtt.eclipse.org", 1883, 60)
client.connect("xxx.216.xx.138", 1883, 60)# 換成自己的IP
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()