建立 MQTT 使用实例 python

环境: centos 7, python3

1 安装消息中间件mosquitto

下载源文件
http://mosquitto.org/download/
编译安装

make
sudo make install

可执行命令文件放在
/usr/local/bin
/usr/local/sbin

配置文件放在
/etc/mosquitto

自定义配置文件 mosquitto.conf

cp mosquitto.conf.example mosquitto.conf

修改端口位 1883

启动服务

/usr/local/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf

2 server

server.py

import paho.mqtt.client as mqtt

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

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, 60)
client.loop_forever()

运行

python3  server.py

3 client

client.py

import paho.mqtt.client as mqtt

HOST = "127.0.0.1"
PORT = 1883

def test():
    client = mqtt.Client()
    client.connect(HOST, PORT, 60)
    client.publish("chat","hello chenfulin",2)
    client.loop_forever()

if __name__ == '__main__':
    test()

运行

python3 client.py

server 程序将会打印 client 发送的数据。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值