建立 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 發送的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章