开始之前:请先安装Paho MQTT Python Client,可以使用pip进行安装:pip install paho-mqtt
客户端订阅消息实例代码(汉字部分需要修改为自己的设备连接信息):
#coding: UTF-8
import paho.mqtt.client as mqtt
import time
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc)) # 打印连接状态
client.subscribe("订阅的主题") # 填写订阅的主题
def on_message(client, userdata, msg):
print(msg.topic+" " + ":" + str(msg.payload)) # 打印接受的消息
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())) # 以当前时间作为client_id
client = mqtt.Client(client_id) # ClientId不能重复,所以使用当前时间
client.username_pw_set("用户名", "密码") # 设置连接用户和密码,必须设置,否则会返回Connected with result code 4
client.on_connect = on_connect
client.on_message = on_message
client.connect("连接地址", 1883, 60) # 1883为服务端口号,如果是安全认证,端口号需要修改为1884
client.loop_forever()
客户端发布消息实例代码(汉字部分需要修改为自己的设备连接信息):
#coding: UTF-8
import time
import paho.mqtt.client as mqtt
import datetime
def on_publish(msg, rc): # 成功发布消息的操作
if rc == 0:
print("publish success, msg = " + msg)
def on_connect(client, userdata, flags, rc): # 连接后的操作 0为成功
print("Connection returned " + str(rc))
user = "用户名" # 用户名
pwd = "密码" # 密码
endpoint = "连接地址" # 连接地址
port = 1883 # 1883为服务端口号,如果是安全认证,端口号需要修改为1884
topic = "发布消息的主题" # 发布消息主题
client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
client = mqtt.Client(client_id) # ClientId不能重复,所以使用当前时间
client.username_pw_set(user, pwd) # 设置用户名,密码
client.connect(endpoint, port, 60) # 连接服务 keepalive=60
client.on_connect = on_connect # 连接后的操作
client.loop_start()
time.sleep(2)
count = 0
while count < 5: # 发布五条消息
count = count + 1
msg = str(datetime.datetime.now())
rc, mid = client.publish(topic, payload=msg, qos=1) # qos
on_publish(msg, rc)
time.sleep(2)
结果测试:
发消息:
收消息: