Python MQTT 实验

Posted 下划线是我

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python MQTT 实验相关的知识,希望对你有一定的参考价值。

Two client:

  • Pub_1.py
    import paho.mqtt.client as mqtt
    import time
    import sys
    import random
    
    
    def on_connect(client, userdata, flags, rc):
        print("connected with result code "+str(rc))
    
    
    def on_publish(client, userdata, mid):
        print("Publish au/csie/5/9/5912/temperture", )
    
    
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_publish = on_publish
    
    
    client.connect("iot.eclipse.org", 1883, 60)
    
    
    while True:
        try:
            with open("C:\Users\86390\Desktop\test_s.txt", "r") as f:
                data = f.readlines()
            # data = random.randint(24, 28)
            # client.publish("au/csie/5/9/5912/tempeture", str(data)+"C")
            print(len(str(data)))
            time.sleep(2)
        except KeyboardInterrupt:
            print("EXIT")
            client.disconnect()
            sys.exit(0)
  • Sub_1.py
    import paho.mqtt.client as mqtt
    import time
    import sys
    import random
    
    
    def on_connect(client, userdata, flags, rc):
        print("Connected with result code"+str(rc))
        client.subscribe("/inode/mychannel")
    
    
    def on_message(client, userdata, msg):
        print(len(str(msg.payload))/1024/1024)
    
    
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    
    client.connect("127.0.0.1", 1883, 60)
    client.loop_forever()

 

 

Publisher and Client:

  • Pub_2.py
    import paho.mqtt.publish as publish
    import time
    
    def transmitMQTT(strMsg):
        strMqttBroker = "localhost"
        # strBroker = "127.0.0.1"
        strMqttChannel = "/inode/mychannel"
        print(len(str(strMsg)))
        publish.single(strMqttChannel, strMsg, hostname=strMqttBroker)
    
    if __name__ == __main__:
        while True:
            transmitMQTT("a"*1024*1024*40)
            time.sleep(0.1)
    
            print (time.time())

     

  • Sub_2.py
    import paho.mqtt.client as mqtt
    import time
    import sys
    import random
    
    
    def on_connect(client, userdata, flags, rc):
        print("Connected with result code"+str(rc))
        client.subscribe("/inode/mychannel")
    
    
    def on_message(client, userdata, msg):
        print(len(str(msg.payload))/1024/1024)
    
    
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    
    client.connect("127.0.0.1", 1883, 60)
    client.loop_forever()

     

坑:

  • 在Windows上正常通信的两个Client, 在虚拟机上sub端接收不到,可能是DNS网管问题。
  • 两个Client通信,必须搭建中间的broker, 但是如果是一个pub, 一个sub,则直接通过本地主机作为broker即可。

以上是关于Python MQTT 实验的主要内容,如果未能解决你的问题,请参考以下文章

Easy IoT实现mqtt实验

TinywebDB+MQTT实现掌控板抢答实验

TinywebDB+MQTT实现掌控板抢答实验

sIoT及安卓app实现mqtt实验

sIoT及安卓app实现mqtt实验

paho.mqtt.python模块怎么安装