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即可。