【MQTT】python MQTT客户端

需要安装的python库

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

测试发布(pub)

 我的MQTT部署在阿里云的服务器上面,所以我在本机上编写了python程序进行测试。

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

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

# encoding: utf-8
import paho.mqtt.client as mqtt

HOST = "101.200.46.138"
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 = "101.200.46.138"
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("www.liefyuan.top", 1883, 60)

client.loop_forever()
发布了583 篇原创文章 · 获赞 96 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/bandaoyu/article/details/90358674