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

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

python测试需要一个发送进程和接收进程,即一个发送客户端和一个接收客户端,如果这两个客户端工作在同一个topic下,那么就能进行消息互通了。

服务器用“iot.eclipse.org”就好了,避免了自己搭建服务器,然后流程还可以跑通。

发送客户端代码:

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

然后运行两个客户端,就可以在接收端收到消息了。

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

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

如果要搭建自己的MQTT服务器,那么回头再说。

玩一玩就好了,不要给服务器增加太多负担哟~

参考资料:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值