【开发者笔记】MQTT python测试笔记

MQTT是基于订阅/发布的物联网协议。python

python测试须要一个发送进程和接收进程,即一个发送客户端和一个接收客户端,若是这两个客户端工做在同一个topic下,那么就能进行消息互通了。服务器

服务器用“iot.eclipse.org”就行了,避免了本身搭建服务器,而后流程还能够跑通。eclipse

发送客户端代码:oop

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

  接收客户端代码:测试

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()

  而后运行两个客户端,就能够在接收端收到消息了。this

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

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

  若是要搭建本身的MQTT服务器,那么回头再说。server

  玩一玩就行了,不要给服务器增长太多负担哟~blog

 

 

参考资料:

  paho-qtt说明文档

相关文章
相关标签/搜索