mqtt 连接测试

code

import paho.mqtt.client as mqtt
import time
import sys


HOST = “1.1.1.1"
PORT = 1883


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
def on_subscribe(client,userdata,mid,granted_qos):
    print("消息发送成功")


client = mqtt.Client(protocol=3)
client.username_pw_set("admin", "password")
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.connect(host=HOST, port = PORT, keepalive=60)  # 订阅频道
time.sleep(1)
i = 0


while True:
    try:
        # 发布MQTT信息
        sensor_data = "test" + str(i)
        client.publish(topic="public", payload=sensor_data.encode("utf-8"), qos=0)
        time.sleep(3)
        i += 1
    except KeyboardInterrupt:
        print("EXIT")
        client.disconnect()
        sys.exit(0)

 

 

 

 

 

 

 

posted @ 2020-12-23 00:42  anobscureretreat  阅读(384)  评论(0编辑  收藏  举报