需要安装的python库
使用python编写程序进行测试mqtt的发布和订阅功能。首先要安装:pip install paho-mqtt
测试发布(pub)
我的mqtt部署在阿里云的服务器上面,所以我在本机上编写了python程序进行测试。
然后在shell里面重新打开一个终端,订阅一个主题为“chat” mosquitto_sub -t chat
在本机上测试远程的mqtt的发布功能就是把自己作为一个发送信息的人,当自己发送信息的时候,所有订阅过该主题(topic)的对象都将收到自己发送的信息。
1
2
3
4
5
6
7
8
9
10
11
12
|
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() |
发布/订阅测试
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
27
|
# -*- 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() |
注解函数:
1
2
3
|
client.connect( self , host, port, keepalive, bind_address) client.publish( self , topic, payload, qos, retain) client.subscribe( self , topic, qos) |
测试订阅(sub)
在本机上编写程序测试订阅功能,就是让自己的程序作为一个接收者,同一个主题没有发布(pub)信息的时候,就自己一直等候。
1
2
3
4
5
6
7
8
9
10
11
12
|
# 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的发布和订阅,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!原文链接:https://blog.csdn.net/xxmonstor/article/details/80479851