龙空技术网

「python」mqtt订阅者和发布者

代码碎片 178

前言:

而今兄弟们对“发布者订阅者”大体比较重视,各位老铁们都需要知道一些“发布者订阅者”的相关知识。那么小编同时在网上网罗了一些对于“发布者订阅者””的相关资讯,希望各位老铁们能喜欢,各位老铁们快快来学习一下吧!

demo说明:

比如一个发布者发送消息给订阅者,那么需要开一个mqtt服务器(Broker),

发布者作为客户端(client)通过mqtt服务器发布(publish)某个主题(topic)的消息(message),

订阅者也作为客户端,连接(connect)到mqtt服务器,

且订阅(subscribe)该主题,就能收到消息。

mqtt服务搭建:

1、选择合适的EMQX版本下载压缩包(百度下载即可),解压后,进入bin目录,启动服务器:emqx.cmd start

启动服务器后,浏览器打开,默认管理账号admin/public即可登录查看

发布者代码:

import timeimport paho.mqtt.client as mqttimport json# 连接mqqt服务def on_connect(client, userdata, flags, rc):    rc_status = [ "连接成功", "协议版本错误", "无效的客户端标识", "服务器无法使用", "用户密码错误", "无授权" ]        if rc == 0:        print("Connected to MQTT Broker!")        print("connect:" , rc_status[rc])    else:        print("Failed to connect, return code %d\n", rc)        print("connect:" , rc_status[rc])# 发布消息函数def on_publish(topic, payload, qos):    mqttclient.publish(topic, payload, qos)def main():    subject = "mqtt/demo"        payload = '这是客户端发送的消息'        print ('发布主题:%s,消息内容:%s'%(subject,payload))        on_publish(subject, payload,qos=0)if __name__ == '__main__':    client_id = 'test_1'    mqtthost = "192.168.0.100"        mqttport = 1883        mqttclient = mqtt.Client(client_id)    mqttclient.on_connect = on_connect    mqttclient.connect(mqtthost, mqttport, 20)    mqttclient.loop_start()    main()

订阅者代码:

import timeimport paho.mqtt.client as mqttimport json# 连接mqqt服务def on_connect(client, userdata, flags, rc):    rc_status = [ "连接成功", "协议版本错误", "无效的客户端标识", "服务器无法使用", "用户密码错误", "无授权" ]        if rc == 0:        print("Connected to MQTT Broker!")        print("connect:" , rc_status[rc])    else:        print("Failed to connect, return code %d\n", rc)        print("connect:" , rc_status[rc])# 订阅消息函数def on_subscribe():    def on_message_come(lient, userdata, msg):        print("订阅主题:", msg.topic)                print("接收消息:", str(msg.payload,'utf-8') ,'\n' )    mqttclient.subscribe("mqtt/demo", qos=0)    mqttclient.on_message = on_message_come # 消息到来处理函数def main():    print ('开始接收订阅主题的消息.\n')    on_subscribe()if __name__ == '__main__':    client_id = 'test_2'    mqtthost = "192.168.0.100"        mqttport = 1883        mqttclient = mqtt.Client(client_id)    mqttclient.on_connect = on_connect    mqttclient.connect(mqtthost, mqttport, 20)    mqttclient.loop_start()    main()

执行:

测试结果:

标签: #发布者订阅者 #订阅者和发布者是什么关系呢