paho-mqtt 实现通信

      paho是实现MQTT通信的多平台多语言的库,支持Python,c++,PHP等,官网地址:paho官网,一般情况下,会使用mosquitto搭建服务器,客户端会使用paho库实现,或者使用mosquitto提供的原始API实现。paho的example比较多,文档写的也好,下到python的代码后,里面就有example。为了快速验证功能,下面的例子使用Python实现。

1.安装paho-mqtt

pip install paho-mqtt

2 订阅消息

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

3发布消息

# 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"})

 

你可能感兴趣的:(MQTT通信,物联网,网络通信)