MQTT协议简单了解

1.MQTT概念

MQTT:消息队列遥测传输协议,是一个基于客户端-服务器的消息发布/订阅传输协议。最大优点在于可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务。
基础概念参考https://www.runoob.com/w3cnote/mqtt-intro.html

2.订阅/发布

MQTT 协议的订阅与发布是基于主题的,直接上代码。
发布者:

import json
import threading
import time

import paho.mqtt.client as mqtt
from paho.mqtt.client import MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, MQTT_LOG_DEBUG


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


def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload.decode()))

def on_log(mqttc, obj, level, buf):
    if level == MQTT_LOG_INFO:
        head = 'INFO'
    elif level == MQTT_LOG_NOTICE:
        head = 'NOTICE'
    elif level == MQTT_LOG_WARNING:
        head = 'WARN'
    elif level == MQTT_LOG_ERR:
        head = 'ERR'
    elif level == MQTT_LOG_DEBUG:
        head = 'DEBUG'
    else:
        head = level
    print('%s: %s' % (head, buf))


def listener():
    topic = "topic2"
    client.subscribe(topic, qos=0)
    client.loop_forever()


if __name__ == '__main__':
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    # client.on_log = on_log
    client.connect('127.0.0.1', 1883, 5)

    th = threading.Thread(target=listener, )
    th.start()

    while True:
        time.sleep(2)
        body = {
            "id": int(time.time() * 1000),
            "type": "111",
            "targetList": ["0", "1"]
        }
        client.publish('topic', payload=json.dumps(body), qos=0)

订阅者:

import paho.mqtt.client as mqtt
import json


# 连接mqtt后调用
def on_connect(client, userdata, flags, rc):
    print("Connected with result code: " + str(rc))


def on_message(client, userdata, msg):
    # 字典
    res = json.loads(msg.payload.decode())
    print(msg.topic + " : " + json.dumps(res))
    if res: # 接收到消息后 发布返回消息
        client.publish('topic2', payload="接收成功", qos=0)


if __name__ == '__main__':
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect('127.0.0.1', 1883, 10)  # 60为keepalive的时间间隔
    client.subscribe('topic', qos=0)
    client.loop_forever()  # 用来保持无穷阻塞调用loop()

订阅者和发布者之间为MQTT服务器,可以是一个应用程序或一台设备,可以:
a.接收客户端的网络连接
b. 接收客户端消息发布
c.向订阅者转发消息
d.处理客户端的订阅和退订请求

代码分析:
发布者连接MQTT服务器,发布指定主题为topic的消息。服务器向订阅该主题的订阅者转发消息,订阅者接收到消息后调用on_message函数,并发布主题为topic2的消息,服务器接收到消息后转发主题为topic2的消息,原来的发布者这时候作为订阅者接收到主题为topic2的消息,调用on_message函数。

你可能感兴趣的:(MQTT,python,客户端)