2019上半年做DR项目的时候用到过mqtt来实现k8s上运行的node和前端web之间的通讯和信息传递。但实际上这个技术主要是用于IoT方面的。
MQTT is a machine-to-machine (M2M)/“Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium.
上文引用自mqtt的官方介绍http://mqtt.org
官方github为https://github.com/mqtt/mqtt.github.io/wiki
划重点: mqtt是一项协议,不是通讯工具。
信息传送机制
MQTT 使用发布(Publish)/订阅 (Subscribe)的讯息传送机制,此机制中包含 4 个主要的元素:
- 主题(
Topic) - 发布者(
Publisher) - 讯息中继站 (
Broker) - 订阅者(
Subscriber)
Publisher 为讯息的来源,传送夹带有 Topic 资讯的讯息至 Broker,Subcriber向Broker索取想要接受到之讯息的Topic。
订阅了相同topic的订阅者将会收到这个Topic下发送的任何消息。
信息中继站Broker一般需要自己搭建。不过这个链接上面有一些免费的公开的Broker可以直接使用,用url作为mqtt server即可,默认端口1883.
https://github.com/mqtt/mqtt.github.io/wiki/public_brokers
代码实现
mqtt接收端:
1 |
import paho.mqtt.client as mqtt |
mqtt发送端:
1 |
import paho.mqtt.client as mqtt |




近期评论