使用python实现mqtt的发布和订阅

 

需要安装的python库

 使用python编写程序进行测试MQTT的发布和订阅功能。首先要安装:pip install paho-mqtt

测试发布(pub)

 我的MQTT部署公司服务器

然后在shell里面重新打开一个终端,订阅一个主题为“chat” mosquitto_sub -t chat

 在本机上测试远程的MQTT的发布功能就是把自己作为一个发送信息的人,当自己发送信息的时候,所有订阅过该主题(topic)的对象都将收到自己发送的信息。 
mqtt_client.py

# encoding: utf-8

import paho.mqtt.client as mqtt

HOST = "ip"
PORT = 1883

def test():
    client = mqtt.Client()
    client.connect(HOST, PORT, 60)
    client.publish("chat","hello liefyuan",2) # 发布一个主题为'chat',内容为‘hello liefyuan’的信息
    client.loop_forever()

if __name__ == '__main__':
    test()
  •  

发布/订阅测试

# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt

MQTTHOST = "ip"
MQTTPORT = 1883
mqttClient = mqtt.Client()


# 连接MQTT服务器
def on_mqtt_connect():
    mqttClient.connect(MQTTHOST, MQTTPORT, 60)
    mqttClient.loop_start()


# publish 消息
def on_publish(topic, payload, qos):
    mqttClient.publish(topic, payload, qos)

# 消息处理函数
def on_message_come(lient, userdata, msg):

    print(msg.topic + " " + ":" + str(msg.payload))


# subscribe 消息
def on_subscribe():
    mqttClient.subscribe("/server", 1)
    mqttClient.on_message = on_message_come # 消息到来处理函数


def main():
    on_mqtt_connect()
    on_publish("/test/server", "Hello Python!", 1)
    on_subscribe()
    while True:
        pass



if __name__ == '__main__':
    main()

  •  

注解函数:

client.connect(self, host, port, keepalive, bind_address)

client.publish(self, topic, payload, qos, retain)

client.subscribe(self, topic, qos)

测试订阅(sub)

 在本机上编写程序测试订阅功能,就是让自己的程序作为一个接收者,同一个主题没有发布(pub)信息的时候,就自己一直等候。

# encoding: utf-8


import paho.mqtt.client as mqtt


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


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("ip", 1883, 60)
client.loop_forever()
  •  

你可能感兴趣的:(mqtt)