博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python MQTT 实验
阅读量:5141 次
发布时间:2019-06-13

本文共 2214 字,大约阅读时间需要 7 分钟。

Two client:

  • Pub_1.py
    import paho.mqtt.client as mqttimport timeimport sysimport randomdef 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_connectclient.on_publish = on_publishclient.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 mqttimport timeimport sysimport randomdef 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_connectclient.on_message = on_messageclient.connect("127.0.0.1", 1883, 60)client.loop_forever()

 

 

Publisher and Client:

  • Pub_2.py
    import paho.mqtt.publish as publishimport timedef 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 mqttimport timeimport sysimport randomdef 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_connectclient.on_message = on_messageclient.connect("127.0.0.1", 1883, 60)client.loop_forever()

     

坑:

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

转载于:https://www.cnblogs.com/ryu-manager/p/9347867.html

你可能感兴趣的文章
数学图形之Boy surface
查看>>
处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“Manag
查看>>
3.浏览器检测
查看>>
01: socket模块
查看>>
Border-radius
查看>>
mysql触发器
查看>>
Redis学习笔记(1)Redis安装和启动
查看>>
淌淌淌
查看>>
5W1H
查看>>
vue2.0中v-on绑定自定义事件
查看>>
javascript中document对象详解
查看>>
未找到导入的项目"盘符:\Microsft.CSharp.targets"。请确认 <Import> 声明中的路径正确,且磁盘上存在该文件。的解决方法...
查看>>
C语言中的static关键字
查看>>
Missing Number
查看>>
MySQL-定时任务
查看>>
自搭的一个系统框架,使用Spring boot+Vue+Element
查看>>
创业之死:97%的创业失败是因为…… . 分类: 项目管理 ...
查看>>
Ubuntu Desktop变为Ubuntu Server服务器版的方法 分类: ...
查看>>
中断处理程序不能使用printf的本质 分类: vxWorks ...
查看>>
布局自适应
查看>>