python mqtt通信(windows)
一、消息队列服务器
这里我用到activemq,可到官网下载 http://activemq.apache.org/
1. 若遇到点击apache-activemq-5.16.2\bin\activemq.bat 出现闪退,64位系统请点击apache-activemq-5.16.2\bin\win64\activemq.bat,启动mqtt服务器
ActiveMQ启动闪退的问题可见 https://blog.csdn.net/pavel101/article/details/79460672
2. ActiveMQ 默认用户名和密码
用户名:admin 密码:admin
可以在/conf/users.properties中寻找。
默认登录地址:http://localhost:8161/admin/,这里mqtt默认端口为1883,ip为192.168.1.103
二、封装客户端
1 import paho.mqtt.client as mqtt
2
3 import logging
4
5 class MqttClient(mqtt.Client):
6
7 def initClient(self, mqttServer, mqttPort, username, password, timeout=10000):
8 logging.basicConfig(level=logging.DEBUG)
9
10 self.mqttServer = mqttServer
11 self.mqttPort = mqttPort
12 self.username_pw_set(username, password=password)
13
14 self.connect(self.mqttServer, self.mqttPort, timeout) # keeplive仅为10000秒
15 self.on_connect = self.on_connect
16
17 def getClient(self):
18 return self.client
19
20 def on_connect(self, client, userdata, flags, rc):
21 linkAddr = client.mqttServer + ":"+ str(client.mqttPort)
22 if rc == 0:
23 logging.info("与mqtt服务器:"+ linkAddr +"连接成功")
24 elif rc == 1:
25 logging.error("协议版本错误")
26 elif rc == 2:
27 logging.error("无效的客户端标识")
28 elif rc == 3:
29 logging.error("服务端无法使用")
30 elif rc == 4:
31 logging.error("与mqtt服务器连接失败: 错误的用户名或密码 ")
32 elif rc == 5:
33 logging.error("登录用户未经授权 ")
34 else:
35 logging.error("与mqtt服务器:%s 连接返回异常结果:%s " % (linkAddr, str(rc)))
36
37 def on_subscribe(self, client, userdata, mid, granted_qos):
38 logging.info("订阅成功: " + str(mid) + " " + str(granted_qos))
39
40 def on_publish(self, client, userdata, mid):
41 logging.info("OnPublish, mid: " + str(mid))
三、下面模拟客户端1和客户端2通信,客户端1发布信息,客户端2接收信息
客户端1代码
1 #!/usr/bin/python
2 import datetime
3 import json
4 import logging
5 import time
6
7 from mqttService.mqttClient import MqttClient
8
9 #------------------客户端1--------------------
10 # ======================================================
11
12
13 # 服务器地址
14 mqttServer = "192.168.1.103"
15 # 通信端口
16 mqttPort = 1883
17 # 订阅主题
18 devTopic = '/devices/dev1'
19 responseDevTopic= '/7.0/dev1'
20
21
22 # 接收客户端2响应信息
23 def on_message(client, userdata, message):
24 curtime = datetime.datetime.now()
25 strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
26 logging.info("%s: 接收 %s 响应信息:主题:%s 内容:%s" %(strcurtime, mqttServer+":"+str(mqttPort), message.topic, str(message.payload, encoding = "utf-8")))
27
28
29 if __name__ == '__main__':
30 logging.basicConfig(level=logging.DEBUG)
31
32 username = "UserName1"
33 password = "PassWord1"
34
35 client = MqttClient()
36 client.initClient(mqttServer, mqttPort, username, password)
37 client.subscribe(responseDevTopic, qos=0) #订阅主题
38 client.on_message = on_message
39
40 msg = 'hello world'
41 for i in range(1000):
42 client.publish(devTopic, payload=msg , qos=0) #发布信息
43 time.sleep(4)
client.loop_forever() # 持续连接
客户端2代码
#!/usr/bin/python
import datetime
import json
import logging from mqttService.mqttClient import MqttClient #------------------客户端2------------------- # 订阅主题
devTopic = '/devices/#'
# 发布主题
responseDevTopicPrefix = '/7.0/' def on_message(client, userdata, message):
curtime = datetime.datetime.now()
strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
recvMsg = message.payload # 获取发送设备的设备ID
topicArr = str(message.topic).split("/")
topicArr = [item for item in filter(lambda x: x != '', topicArr)] # 去除空串
deviceId = topicArr[1] logging.info("%s: 接收硬件装置 %s 信息:主题: %s 内容: %s" %(strcurtime, deviceId, message.topic, recvMsg)) # 发送响应回硬件终端
client.publish(responseDevTopicPrefix +deviceId, payload="收到数据"+recvMsg, qos=0)if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG) mqttAddr = '192.168.1.103'
mqttPort = 1883 username = "UserName2"
password = "PassWord2"
# 与客户端1通信
client = MqttClient()
client.initClient(mqttAddr, mqttPort, username, password)
client.subscribe(devTopic, qos=0)
client.on_message = on_message
client.loop_start() # 开始监听
# 阻塞主程序
while True:
pass
python mqtt通信(windows)的更多相关文章
- MQTT(一)C#使用 MQTTnet 快速实现 MQTT 通信(文末有完整Demo下载)
https://blog.csdn.net/panwen1111/article/details/79245161 目录MQTT(一)C#使用 MQTTnet 快速实现 MQTT 通信(文末有完整De ...
- 使用 MQTTnet 快速实现 MQTT 通信
1 什么是 MQTT ? MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是 IBM 开发的一个即时通讯协议,有可能成为物联网的重要组成部分.MQT ...
- Python环境搭建(windows)
Python环境搭建(windows) Python简介 Python(英国发音:/ˈpaɪθən/ 美国发音:/ˈpaɪθɑːn/),是一种面向对象.直译式计算机编程语言,具有近二十年的发展历史,成 ...
- Python Socket通信原理
[Python之旅]第五篇(一):Python Socket通信原理 python Socket 通信理论 socket例子 摘要: 只要和网络服务涉及的,就离不开Socket以及Socket编 ...
- 如何实现 C/C++ 与 Python 的通信?
属于混合编程的问题.较全面的介绍一下,不仅限于题主提出的问题.以下讨论中,Python指它的标准实现,即CPython(虽然不是很严格) 本文分4个部分 1. C/C++ 调用 Python (基础篇 ...
- WiFi-ESP8266入门http(3-4)网页一键配网(1若为普通wifi直连 2若为西电网页认证自动网页post请求连接)+网页按钮灯控+MQTT通信
网页一键配网(1若为普通wifi直连 2若为西电网页认证自动网页post请求连接)+网页按钮灯控+MQTT通信 工程连接:https://github.com/Dongvdong/ESP8266_H ...
- Fix Python 3 on Windows error Microsoft Visual C++ 14.0 is required
Fix Python 3 on Windows error Microsoft Visual C++ 14.0 is required Fix the error for Python 3.6 and ...
- C/C++ 与 Python 的通信
作者:Jerry Jho链接:https://www.zhihu.com/question/23003213/answer/56121859来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商 ...
- python MySQLdb在windows环境下的快速安装
python MySQLdb在windows环境下的快速安装.问题解决方式 使用python访问mysql,需要一系列安装 linux下MySQLdb安装见 Python MySQLdb在Linux下 ...
随机推荐
- kafka之一:kafka简介
现在从事java开发的同学,不论是在面试过程中还是在日常的工作中,肯定会碰到消息队列的情况,市面上消息队列有很多:kafka.rocketMQ.rabbitMQ.zeroMQ等,从本篇博客起计划分享一 ...
- AtCoder Regular Contest 121 D - 1 or 2
题目链接:点我点我 Problem Statement Snuke has a blackboard and NN candies. The tastiness of the ii-th candy ...
- rabbit_消费者
import pika import json import time import os import ast import uuid import time import json import ...
- nginx基础概念
nginx基础概念(100%) connection¶ 在nginx中connection就是对tcp连接的封装,其中包括连接的socket,读事件,写事件.利用nginx封装的connection, ...
- openresty - nginx - 配置
local function local_print(str) local dbg = io.open("conf/lua/logs/output.txt", "a+&q ...
- 前端工具 | JS编译器 Brace 使用教程
前言 开发人员一般是在电脑上面安装了IDE完成日常的开发任务,因为项目业务需求,用户想要在线写JS脚本,纯粹的字符串,很"费用户".那就需要一个在线JS编译器,需要轻量级,好用,语 ...
- THINKPHP_(4)_TP模型中with、withJoin和多层关联的深入分析
1.个人之前博文: TP模型的多表关联查询和多表字段的关键字搜索 TP6中实现多层关联,第一个表关联第二个表查询出的数据,再关联第三个表 2.withJoin的特性 2.1 第一个特性 在TP模型的多 ...
- TVM性能评估分析(五)
TVM性能评估分析(五) Figure 3. A futher speed up with operator fusion Table 1. Performance issue of cuBLAS ...
- 视频教学动作修饰语:CVPR2020论文解析
视频教学动作修饰语:CVPR2020论文解析 Action Modifiers: Learning from Adverbs in Instructional Videos 论文链接:https://a ...
- GPU加速:宽深度推理
GPU加速:宽深度推理 Accelerating Wide & Deep Recommender Inference on GPUs 推荐系统推动了许多最流行的在线平台的参与.随着为这些系统提 ...