自建mqtt服务器并测试

以下发布代码可以将信息发布到上图的接受端

import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")

client = mqtt.Client()
client.on_connect = on_connect
client.connect("mqtt.ihand.work", 20246, 60)

# 每间隔 1 秒钟向 raspberry/topic 发送一个消息,连续发送 5 次
for i in range(5):
    # 四个参数分别为:主题,发送内容,QoS, 是否保留消息
    client.publish('raspberry/topic', payload=i, qos=0, retain=False)
    print(f"send {i} to raspberry/topic")
    time.sleep(1)

client.loop_forever()
因paho-mqtt官方版本更新,代码需要做相应修改,具体如下:
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code: " + str(rc))

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_connect = on_connect
client.on_message = on_message
client.connect('192.168.100.161', 1883, 600) # 600为keepalive的时间间隔
client.publish('raspberry', payload='amazing', qos=0)