Python MQTT客户端实现

2023-01-31 02:01:48 python mqtt 客户端

如需转载请标明出处:Http://blog.csdn.net/itas109
QQ技术交流群:12951803

1.安装paho-MQtt

使用python Package Index (PyPi)

pip install paho-mQtt

使用virtualenv

virtualenv paho-mqtt
source paho-mqtt/bin/activate
pip install paho-mqtt

或者编译源代码

git clone https://GitHub.com/eclipse/paho.mqtt.Python

使用源码安装

cd paho.mqtt.python
python setup.py install

2. Demo

接收数据

import paho.mqtt.client as mqtt
import time

HOST = "127.0.0.1"
PORT = 61613

def client_loop():
    client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    client = mqtt.Client(client_id)    # ClientId不能重复,所以使用当前时间
    client.username_pw_set("admin", "123456")  # 必须设置,否则会返回「Connected with result code 4」
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(HOST, PORT, 60)
    client.loop_forever()

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")

def on_message(client, userdata, msg):
    print(msg.topic+" "+msg.payload.decode("utf-8"))

if __name__ == '__main__':
    client_loop()

注意,client_id是必须的,并且是唯一的。否则可能会出现如下错误:

[WinError 10054] 远程主机强迫关闭了一个现有的连接。


发布数据

# import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import time

HOST = "127.0.0.1"
PORT = 61613
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("test")

def on_message(client, userdata, msg):
    print(msg.topic+" "+msg.payload.decode("utf-8"))

if __name__ == '__main__':
    client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    # client = mqtt.Client(client_id)    # ClientId不能重复,所以使用当前时间
    # client.username_pw_set("admin", "123456")  # 必须设置,否则会返回「Connected with result code 4」
    # client.on_connect = on_connect
    # client.on_message = on_message
    # client.connect(HOST, PORT, 60)
    # client.publish("test", "你好 MQTT", qos=0, retain=False)  # 发布消息

    publish.single("test", "你好 MQTT", qos = 1,hostname=HOST,port=PORT, client_id=client_id,auth = {'username':"admin", 'passWord':"123456"})

3.结果

接收

这里写图片描述

发送

这里写图片描述

Reference
https://pypi.python.org/pypi/paho-mqtt


觉得文章对你有帮助,可以扫描二维码捐赠给博主,谢谢!
在这里插入图片描述
如需转载请标明出处:http://blog.csdn.net/itas109
QQ技术交流群:12951803

相关文章