paho-mqtt

mqtt 参考: https://pypi.org/project/paho-mqtt/

#服务端

[root@localhost ~]# cat mqtt_server.py

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
 
idx = 0 #往paho/temperature 一直发送内容
while True:
    print("send success")
    publish.single("paho/temperature",
               payload="this is message:%s"%idx,
               hostname="iot.eclipse.org",
               client_id="lora1",
               # qos = 0,
               # tls=tls,
               port=1883,
               protocol=mqtt.MQTTv311)
    idx += 1

#客户端

[root@localhost ~]# cat mqtt_client.py 

import paho.mqtt.client as mqtt
 
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
 
 
# The callback for when a PUBLISH message is received from the server.
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("iot.eclipse.org", 1883, 60) #订阅频道
client.subscribe("paho/temperature")
 
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

#启动服务端,再启动客户端

 

#服务端一直发送信息
[root@localhost ~]# python3 mqtt_server.py 
send success
send success
send success
send success
send success
send success
send success
send success
send success
send success
send success


#客户端接收信息
[root@localhost ~]# python3 mqtt_client.py 
Connected with result code 0
paho/temperature b'this is message:125'
paho/temperature b'this is message:126'
paho/temperature b'this is message:127'
paho/temperature b'this is message:128'
paho/temperature b'this is message:129'
paho/temperature b'this is message:130'

备注:

MQTT服务器不负责存储数据,需要编写额外的接收客户端来接收数据、分析、入库等。

MQTT服务器用的是iot.eclipse.org,如果碰巧两个人在用同一个频道,那可能收到别人的消息哦~

 搭建mqtt服务器

参考:

http://emqtt.com/docs/v2/install.html

https://blog.csdn.net/qq_37258787/article/details/79776663

 

猜你喜欢

转载自www.cnblogs.com/nulige/p/8993719.html
今日推荐