python3 使用paho-mqtt

python版本:python3.8

mqtt库:paho-mqtt 1.6.1

 

一,消息发布

创建pub.py,写入以下代码

复制代码
import time
from paho.mqtt import client as mqtt_client


# broker服务器,远程中间人的主机或IP
broker = 'localhost'
# 端口,默认端口是1883
port = 1883
# 主题(要和订阅端保持一致)
topic = 'topic1'
# 客户端id(随机字符串)
client_id = '001'

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print(f"Failed to connect, return code {rc}")

def conn_mqtt():
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"msg of {msg_count}!"
        res = client.publish(topic=topic, payload=msg, qos=1)
        if res[0] == 0:
            print(f"send {msg} successful!")
        else:
            print("Fail to send msg!")
        msg_count += 1

if __name__ == "__main__":
    client = conn_mqtt()
    publish(client)
复制代码

 

二,消息接收(消息订阅)

创建文件sub.py,写入以下代码

复制代码
from paho.mqtt import client as mqtt_client


broker = 'localhost'
port = 1883
topic = 'topic1'
client_id = '002'


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print(f"Failed to connect, return code {rc}")

def conn_mqtt():
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def on_message(client, userdata, msg):
    print(f"Received {msg.payload.decode()}!")

def subscribe(client):
    client.subscribe(topic=topic, qos=1)
    client.on_message = on_message
    client.loop_forever()

if __name__ == "__main__":
    client = conn_mqtt()
    subscribe(client)
复制代码

 注意:qos参数值说明

qos=0,最多发送一次。

qos=1,最少发送一次

qos=2,只发送一次,并且一定能送到

 

三,启动

 

四,MQTT连接错误码

rc=0:连接成功

rc=1:协议版本不接受

rc=2:无效客户端标识符被拒绝

rc=3:服务不可用

rc=4:用户名或密码错误

rc=5:无权连接

posted @   xqs42b  阅读(688)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示