client端
建立连接
broker tools.emqx.io/
import paho.mqtt.client as mqtt
def on_subscribe(client, userdata, mid, granted_qos):
pass
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
def on_message(client, userdata, msg):
print('topic:', msg.topic)
print('msg:', str(msg.payload))
# .......mqtt连接........ #
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password") # 用户名和密码设置
client.on_connect = on_connect # 连接递归
client.on_message = on_message # 消息递归
client.on_subscribe = on_subscribe
client.connect(host="broker.emqx.io", port=8083, keepalive=60) # 连接
time.sleep(1)
订阅
client.subscribe(topic="testtopic/testandy", qos=0) # 订阅主题
发布
client.publish(topic="testtopic/testandy", payload="123", qos=0)
完整代码
import time
import paho.mqtt.client as mqtt
import json
def on_subscribe(client, userdata, mid, granted_qos):
pass
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
def on_message(client, userdata, msg):
print('topic:', msg.topic)
print('msg:', str(msg.payload))
# .......mqtt连接........ #
client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password") # 用户名和密码设置
client.on_connect = on_connect # 连接
client.on_message = on_message # 消息
client.on_subscribe = on_subscribe
client.connect(host="broker.emqx.io", port=1883, keepalive=60) # 连接
time.sleep(1)
while True:
client.subscribe(topic="testtopic/test", qos=0) # 订阅主题
client.loop_start()
time.sleep(10)
服务端
最基础的填个名字即可测试