重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
需要先下载外部包
坚守“ 做人真诚 · 做事靠谱 · 口碑至上 · 高效敬业 ”的价值观,专业网站建设服务10余年为成都餐厅设计小微创业公司专业提供企业网站建设营销网站建设商城网站建设手机网站建设小程序网站建设网站改版,从内容策划、视觉设计、底层架构、网页布局、功能开发迭代于一体的高端网站建设服务。
pip install paho-mqtt
import paho.mqtt.client as mqtt
HOST = "192.168.44.31"
PORT = 1883
def Publish_Message():
client = mqtt.Client()
client.username_pw_set(username='admin', password='public') # 用于添加了插件认证方式后
client.connect(HOST, PORT, 60)
for x in range(10):
Message = "hello" + str(x)
client.publish("services", Message, 0) # 发布一个主题为'services',内容为‘hello x’的信息
# time.sleep(10)
client.loop_forever() # 保持连接状态
if __name__ == '__main__':
Publish_Message()
发布者,主要内容:publish("topic_name","utf8_message",Qos)
- Qos:0 --> 发送者只发送一次消息,不进行重试,Broker不会返回确认消息。Broker可能没有接收到消息。(默认)
- Qos:1 --> 发送者最少发送一次消息,确保消息达到Broker,Broker需要返回确认消息PUBACK。Broker可能接收到重复消息。
- Qos:2 --> 使用两阶段确认来保证消息的不丢失和不重复。Broker肯定会接收到消息,且只收到一次。
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc)) # rc表示返回来的状态值
client.subscribe("services")
def on_message(client, userdata, msg):
print(msg.topic+" " + ":" + str(msg.payload))
if __name__ == "__main__":
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username='admin', password='public') # 用于添加了插件认证方式后
client.connect("192.168.44.31", 1883, 60)
client.loop_forever()
订阅者,信息的产出在msg.payload
rc值代表的含义:
0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused.