MQTT是一個輕量級的消息協議。從2014年12月IOIT大會上獲得的消息,該協議已經被OASIS標準組織接收,成立了專門的工做組,以意味着該規範正式走向了標準化之路。node
目前MQTT的標準組織官網:http://www.mqtt.org,裏面列出了不少支持的軟件相關資源。python
一個輕量級的MQTT服務器是:http://www.mosquitto.org,能夠運行ARM/MIPS的嵌入式linux系統上,如OpenWRT。linux
不少客戶端模塊如今被Eclipse基金會接管,發展很快。全部的語言支持客戶端在這裏:http://git.eclipse.org/c/paho/git
下面介紹基於python的MQTT的客戶端的安裝:
shell
git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git cd org.eclipse.paho.mqtt.python sudo python setup.py install
注意,若是使用Sublime,最好到裏面的控制檯進行安裝,缺省運行在獨立的環境中,跟系統的控制檯安裝的程序不同。服務器
而後,發送消息:eclipse
#!/usr/bin/python # This shows a service of an MQTT subscriber. # Copyright (c) 2010-2015, By openthings@163.com. import sys import datetime import socket, sys import paho.mqtt.publish as publish def transmitMQTT(strMsg): #strMqttBroker = "localhost" strBroker = "112.124.67.178" strMqttChannel = "/inode/mychannel" print(strMsg) publish.single(strMqttChannel, strMsg, hostname = strMqttBroker) if __name__ == '__main__': transmitMQTT("Hello,MQTT Proxy, I am client inside python.") print "Send msg ok."
建立一個MQTT服務器程序:socket
#!/usr/bin/python # This shows a service of an MQTT subscriber. # Copyright (c) 2010-2015, By openthings@163.com. import sys import datetime import socket, sys #====================================================== #MQTT Initialize.-------------------------------------- try: import paho.mqtt.client as mqtt except ImportError: print("MQTT client not find. Please install as follow:") print("git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git") print("cd org.eclipse.paho.mqtt.python") print("sudo python setup.py install") #====================================================== def on_connect(mqttc, obj, rc): print("OnConnetc, rc: "+str(rc)) def on_publish(mqttc, obj, mid): print("OnPublish, mid: "+str(mid)) def on_subscribe(mqttc, obj, mid, granted_qos): print("Subscribed: "+str(mid)+" "+str(granted_qos)) def on_log(mqttc, obj, level, string): print("Log:"+string) def on_message(mqttc, obj, msg): curtime = datetime.datetime.now() strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S") print(strcurtime + ": " + msg.topic+" "+str(msg.qos)+" "+str(msg.payload)) on_exec(str(msg.payload)) def on_exec(strcmd): print "Exec:",strcmd strExec = strcmd #===================================================== if __name__ == '__main__': mqttc = mqtt.Client("mynodeserver") mqttc.on_message = on_message mqttc.on_connect = on_connect mqttc.on_publish = on_publish mqttc.on_subscribe = on_subscribe mqttc.on_log = on_log #strBroker = "localhost" strBroker = "112.124.67.178" mqttc.connect(strBroker, 1883, 60) mqttc.subscribe("/inode/mychannel", 0) mqttc.loop_forever()