7. 使用Python开发MQTT客户端
2023-09-11 14:20:02 时间
构建python客户端
import paho.mqtt.client as mqtt
class MqttClient:
def __init__(self, host, port,mqttClient):
self._host = host
self._port = port
self._mqttClient = mqttClient
# 连接MQTT服务器
def on_mqtt_connect(self, username="tester", password="tester"):
self._mqttClient.username_pw_set(username, password)
self._mqttClient.connect(self._host, self._port, 60)
self._mqttClient.loop_start()
# publish 消息
def on_publish(self, topic, msg, qos):
self._mqttClient.publish(topic, msg, qos)
# 消息处理函数
def on_message_come(client, userdata, msg):
print(msg.topic + " " + ":" + str(msg.data))
# subscribe 消息
def on_subscribe(self, topic):
self._mqttClient.subscribe(topic, 1)
self._mqttClient.on_message = self.on_message_come # 消息到来处理函数
'''
def main():
self.on_mqtt_connect()
on_publish("/test/server", "Hello Python!", 1)
self.on_subscribe()
print("connect success!\n")
while True:
pass
'''
if __name__ == '__main__':
# main()
host = "123.57.8.28"
port = 1883
topic = "CarTest"
# msg = "Hello Python!"
qos = 1
username = "tester"
password = "tester"
mqttClient = mqtt.Client("tester")
client = MqttClient(host, port, mqttClient)
client.on_mqtt_connect(username, password)
# client.on_publish(topic, msg, qos)
client.on_subscribe(topic)
'''
# 多客户端连接
mqttClient_2 = mqtt.Client("tester-2")
username_2 = username + '2'
password_2 = password + '2'
client_2 = MqttClient(host, port, mqttClient_2)
client_2.on_mqtt_connect(username_2, password_2)
client_2.on_subscribe(topic)
'''
print("connect success!\n")
while True:
pass
连接测试
连接成功
参考文档:
使用python实现mqtt的发布和订阅
相关文章
- Python redis客户端调用lua
- Python视觉深度学习系列教程 第一卷 第2章 什么是深度学习
- [LINK]Python服务器开发一:python基础
- Python的5大就业方向,学会一个都是赚
- Python:利用python语言实现18位身份证号码和15位身份证号码相互转换
- Python编程语言学习:python中与数字相关的函数(取整等)、案例应用之详细攻略
- Python:python语言中与时间有关的库函数简介、安装、使用方法(获取当前时间/计算程序块前后运行时间/模型训练时间或耗费时间)之详细攻略
- Python之tkinter:动态演示调用python库的tkinter带你进入GUI世界(Menu的Command)
- Python语言学习:解决python版本升级问题集合(python2系列→Python3系列)导致错误的总结集合
- Python之多线程:python多线程设计之同时执行多个函数命令详细攻略
- Python语言学习之数值、小数、空格那些事:python和数值、小数、空格的使用方法之详细攻略
- 假如你每天花2小时来自学python,91天之后你将会感谢自己的努力
- 〖Python 数据库开发实战 - Redis篇④〗- Redis命令行客户端与图形客户端的简单使用
- 提高 Python 代码的可读性,你需要知道这10个技巧
- ctf.bobbydylan python解密
- python 快速排序-代码示例
- python之mqtt客户端(亲测可用)
- python里使用asyncore创建时间服务客户端
- 4款火热的Python自动化测试框架,谁才是你的唯一?
- Python快速上手系列--字符串--详解篇
- Python小白的数学建模课-22.插值方法
- python小游戏——推箱子代码开源
- Python .py 文件打包成 .exe 文件(Windows平台,python 3.x)