mqtt精简应用python物联网
直接上代码
pub.py;向已建立好的mqtt服务,发送消息
import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code: " + str(rc)) 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('mqtt.eclipseprojects.io', 1883, 600) i=20 while i>0: i-=1 client.publish('fifa', payload='next_sub,%s'%i, qos=0)
print('send,%s'%i)
client.loop_forever()
sub.py;当mqtt服务已建立,可以接收消息。
import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code: " + str(rc)) 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('mqtt.eclipseprojects.io', 1883, 600) client.subscribe('fifa', qos=0) client.loop_forever()
mqtt.eclipseprojects.io,是别人已搭建的mqtt服务器地址,如果想用自己的,可以自行搭建mqtt服务器。
pub_sub.py 收!发!
import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code: " + str(rc)) 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('mqtt.eclipseprojects.io', 1883, 600) client.subscribe('fifa', qos=0) i=20 while i>0: i-=1 client.publish('fifa', payload='next_sub,%s'%i, qos=0) print('send_pub,%s'%i) client.loop_forever()