【本文出處: http://blog.csdn.net/leytton/article/details/52782523】
1、安裝模塊
paho.mqtt.python開源地址:https://github.com/eclipse/paho.mqtt.python
下載並解壓,打開目錄執行命令安裝模塊
python setup.py install2、Python代碼
#-*-coding:utf-8-*-
import paho.mqtt.client as mqtt
# 當連接上服務器后回調此函數
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# 放在on_connect函數里意味着
# 重新連接時訂閱主題將會被更新
client.subscribe("topic/sub")
# 從服務器接受到消息后回調此函數
def on_message(client, userdata, msg):
print("主題:"+msg.topic+" 消息:"+str(msg.payload))
client = mqtt.Client()
#參數有 Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
client.on_connect = on_connect #設置連接上服務器回調函數
client.on_message = on_message #設置接收到服務器消息回調函數
client.connect("iot.eclipse.org", 1883, 60) #連接服務器,端口為1883,維持心跳為60秒
client.loop_forever()
3、其他接口
client.disconnect() #斷開連接
client.publish(topic, payload=None, qos=0, retain=False) #發布消息
def on_disconnect(client, userdata, rc):
if rc != 0:
print("Unexpected disconnection.")
mqttc.on_disconnect = on_disconnect ##設置與服務器斷開連接回調函數
def on_publish(client, userdata, mid): #發布消息完成回調函數
...
4、參考文獻
paho.mqtt.python開源地址:https://github.com/eclipse/paho.mqtt.python
