说明:
本文基于上篇博客:详介 MQTT 服务器的搭建与客户端连接 ,下面来使用 python 编写客户端连接服务器,并实现消息的发布和订阅。
phthon 编写工具 pychar 安装步骤:https://zhuanlan.zhihu.com/p/108439489
File
——> Settings...
。Python Interpreter
,再点击 +
添加包。paho-mqtt
并选中,然后点击 Install Package
安装包。1)添加 py 文件
Python Package
(右击 hello
项目 ——> New
——> Python Package
)。_init_.py
文件 ——> Refactor
——> Rename...
)。hello
包 ——> New
——> Python File
)①代码编写
import time
import sys
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
def on_subscribe(client,userdata,mid,granted_qos):
print("消息发送成功")
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.connect(host="192.168.43.98", port = 61613, keepalive=60) # 订阅频道
time.sleep(1)
i = 0
#循环发布消息
while True:
try:
# 发布MQTT信息
sensor_data = "test" + str(i)
client.publish(topic="public", payload=sensor_data, qos=0)
time.sleep(5)
i += 1
except KeyboardInterrupt:
print("EXIT")
client.disconnect()
sys.exit(0)
client_accept.py 编写如下代码:
import time
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("连接成功")
print("Connected with result code " + str(rc))
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_message = on_message
client.connect(host="192.168.43.98", port = 61613, keepalive=60) # 订阅频道
time.sleep(1)
# client.subscribe("public")
client.subscribe([("public", 0), ("test", 2)])
client.loop_forever()
②运行结果:
①编写代码
import sys
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
def on_subscribe(client,userdata,mid,granted_qos):
print("消息发送成功")
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.connect(host="192.168.43.98", port = 61613, keepalive=60) # 订阅频道
time.sleep(1)
i = 0
while True:
sensor_data=input("请输入要发表消息内容(0表示退出):")
if(sensor_data=='0'):
break
try:
# 发布MQTT信息
client.publish(topic="weather", payload=sensor_data, qos=0)
time.sleep(5)
# i += 1
except KeyboardInterrupt:
print("EXIT")
client.disconnect()
sys.exit(0)
②运行结果:
MQTT | REST |
---|---|
TCP协议 | TCP协议 |
长连接 | 短连接 |
适合做设备反向控制 | 不适合做设备实时反向控制 |
实时性控制 | 实时性控制不是很好 |
主要应用于各大物联网平台 | 主要应用于各种 API |
编写MQTT客户端程序——python