版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zym326975/article/details/82108487
基于Apollo的MQTT协议服务器端搭建流程请参考我的文章:https://blog.csdn.net/zym326975/article/details/82081717
为了实现基于Python的MQTT客户端,需要安装paho-mqtt:pip install paho-mqtt
基于Python的MQTT客户端订阅者代码的实现
import paho.mqtt.client as mqtt
import time
HOST = "127.0.0.1"
PORT = 61613
def client_loop():
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
client = mqtt.Client(client_id) #client_id不能重复,所以使用当前时间
client.username_pw_set("admin", "password") #必须设置,否则会返回「Connected with result code 4」
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST, PORT, 60)
client.loop_forever()
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("test")
def on_message(client, userdata, msg):
print(msg.topic+" "+msg.payload.decode("utf-8"))
if __name__ == '__main__':
client_loop()
基于Python的MQTT客户端发布者代码的实现
import paho.mqtt.publish as publish
import time
HOST = "127.0.0.1"
PORT = 61613
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("test")
def on_message(client, userdata, msg):
print(msg.topic+" "+msg.payload.decode("utf-8"))
if __name__ == '__main__':
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
publish.single("test", "你好 MQTT", qos=1, hostname=HOST,port=PORT,client_id=client_id, auth = {'username':"admin", 'password':"password"})