当前位置:   article > 正文

基于python的MQTT和环信即时通信的MQTT通信_python on_message存储

python on_message存储

代码如下:

# -*- 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的值

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/188554
推荐阅读
相关标签
  

闽ICP备14008679号