MQTT协议 Python客户端
【本文出处: 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