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 mqttimport 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_connectclient.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 successsend successsend successsend successsend successsend successsend successsend successsend successsend successsend success#客户端接收信息[root@localhost ~]# python3 mqtt_client.py Connected with result code 0paho/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
软件下载:
使用方法参考:
https://blog.csdn.net/nicholaszao/article/details/79211965