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

veforever 2019-05-05

需要安装的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()

总结

以上所述是小编给大家介绍的使用python实现mqtt的发布和订阅,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对安科网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关推荐