赞
踩
代码如下:
# -*- coding: utf-8 -*-
# 以下代码在2021年10月21日 python3.10环境下运行通过
import paho.mqtt.client as mqtt
import time
HOST = "xxxxx.xxx.mqtt.chat"
PORT = 1883
client_id = "xxxxxxxx@xxxx"
#连接并订阅回调函数,在连接时会调用
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("Myled") # 订阅消息
#消息接收回调函数,在其他MQTT客户端和本客户端发起订阅消息后会触发
def on_message(client, userdata, msg):
print("主题:"+msg.topic+" 消息:"+str(msg.payload.decode('utf-8')))
#订阅成功回调函数,在发起订阅后会触发
def on_subscribe(client, userdata, mid, granted_qos):
print("On Subscribed: qos = %d" % granted_qos)
# 失去连接回调函数,断开连接时会触发
def on_disconnect(client, userdata, rc):
if rc != 0:
print("Unexpected disconnection %s" % rc)
client = mqtt.Client(client_id)
client.username_pw_set("hxm", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxhIEhgpnAR7JMp_cVgpy5yAwMAAAF_m9h2BDeeSAABkc6dqIpUjy3N6jOixZTcXRaw6GxjU678xFwcKpEwrQ")
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.on_disconnect = on_disconnect
client.connect(HOST, PORT, 60)
#client.loop_forever()
run = True
client.loop_start()
while run:
time.sleep(2)
client.subscribe("Myled0")#订阅,会在回调函数里接收的
#client.publish("Myled0",100)#发布
说明:1、xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxhIEhgpnAR7JMp_cVgpy5yAwMAAAF_m9h2BDeeSAABkc6dqIpUjy3N6jOixZTcXRaw6GxjU678xFwcKpEwrQ是环信的
查看token获取的,相当于密码
2、查询信息用订阅,然后其回调函数来接收;上传信息用发布
3、client_id = "xxxxxxxx@xxxx"z中前面是自己取的值,@后面的是环信的AppID的值
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。