mqtt简介

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 资讯的讯息至 BrokerSubcriberBroker索取想要接受到之讯息的Topic

订阅了相同topic的订阅者将会收到这个Topic下发送的任何消息。

信息中继站Broker一般需要自己搭建。不过这个链接上面有一些免费的公开的Broker可以直接使用,用url作为mqtt server即可,默认端口1883.

https://github.com/mqtt/mqtt.github.io/wiki/public_brokers

代码实现

mqtt接收端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import paho.mqtt.client as mqtt


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

# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("TEST")

# 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("test.mosquitto.org", 1883, 60)
client.connect("test.mosquitto.org", 1883, 60)

# 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()

mqtt发送端:

1
2
3
4
5
6
7
import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect("test.mosquitto.org", 1883, 60)
print("here")
client.publish("TEST","This is a test message.")
client.disconnect()