欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python简单应用mqtt

程序员文章站 2022-07-12 21:12:22
...

一.搭建mqtt服务器

  1. 推荐使用EMQX
  2. 下载地址(windows版本):https://www.emqx.io/downloads/broker/v4.1-rc.2/emqx-windows-v4.1-rc.2.zip
  3. 启动mqtt服务器 :D:>\emqx\bin>emqx.cmd start
  4. 关闭mqtt服务器 :D:>\emqx\bin>emqx.cmd stop
  5. 访问地址:http://127.0.0.1:18083
  6. 用户名/密码:admin/public

二.编写代码

2.1 安装mqtt模块

pip install paho-mqtt

2.2 发布客户端

发布客户端:publish.py

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code: " + str(rc))

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect('127.0.0.1', 1883, 600) # 600为keepalive的时间间隔
client.publish('测试', payload='测试通过啦', qos=0)

2.3 接收客户端

接收客户端:subscribe.py

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code: " + str(rc))

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.connect('127.0.0.1', 1883, 600) # 600为keepalive的时间间隔
client.subscribe('测试', qos=0)
client.loop_forever() # 保持连接