python版本:python3.8
mqtt库:paho-mqtt 1.6.1
一,消息发布
创建pub.py,写入以下代码
import time from paho.mqtt import client as mqtt_client # broker服务器 broker = 'localhost' # 端口 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, msg) 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) client.on_message = on_message client.loop_forever() if __name__ == "__main__": client = conn_mqtt() subscribe(client)
三,启动
标签:__,print,mqtt,client,connect,msg,paho,python3 From: https://www.cnblogs.com/xianqingsong/p/16610342.html