paho-mqtt


mqtt 參考:

https://pypi.org/project/paho-mqtt/

https://github.com/eclipse/paho.mqtt.python

 

#服務端

[root@localhost ~]# cat mqtt_server.py

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
 
idx = 0 #往paho/temperature 一直發送內容
while True:
    print("send success")
    publish.single("paho/temperature",
               payload="this is message:%s"%idx,
               hostname="iot.eclipse.org",
               client_id="lora1",
               # qos = 0,
               # tls=tls,
               port=1883,
               protocol=mqtt.MQTTv311)
    idx += 1

#客戶端

[root@localhost ~]# cat mqtt_client.py 

import paho.mqtt.client as mqtt
 
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
 
 
# The callback for when a PUBLISH message is received from the server.
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("iot.eclipse.org", 1883, 60) #訂閱頻道
client.subscribe("paho/temperature")
 
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

#啟動服務端,再啟動客戶端

#服務端一直發送信息
[root@localhost ~]# python3 mqtt_server.py 
send success
send success
send success
send success
send success
send success
send success
send success
send success
send success
send success


#客戶端接收信息
[root@localhost ~]# python3 mqtt_client.py 
Connected with result code 0
paho/temperature b'this is message:125'
paho/temperature b'this is message:126'
paho/temperature b'this is message:127'
paho/temperature b'this is message:128'
paho/temperature b'this is message:129'
paho/temperature b'this is message:130'

備注:

MQTT服務器不負責存儲數據,需要編寫額外的接收客戶端來接收數據、分析、入庫等。

MQTT服務器用的是iot.eclipse.org,如果碰巧兩個人在用同一個頻道,那可能收到別人的消息哦~

 

 搭建mqtt服務器

參考:

http://emqtt.com/docs/v2/install.html

https://blog.csdn.net/qq_37258787/article/details/79776663

 

二、Mosquitto安裝和使用

 https://lanseyujie.com/post/mosquitto-installation-and-usage.html

 

三、安裝mqttfx(用於測試mqtt-服務器)

相當於部署一個mqtt-server

軟件下載:

http://www.jensd.de/apps/mqttfx/1.7.0/

使用方法參考:

https://blog.csdn.net/nicholaszao/article/details/79211965

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM