前提:mqtt消息服务器
一、pip install paho-mqtt
二、写一个推送客户端 Publish.py
1 # __author: gy-chen 2 # data: 2020/5/23 3 # -*- coding: UTF-8 -*- 4 5 6 import paho.mqtt.client as mqtt 7 8 9 def on_connect(client, userdata, flags, rc): 10 print("Connected with result code: " + str(rc)) 11 12 13 def on_message(client, userdata, msg): 14 print(msg.topic + " " + str(msg.payload)) 15 16 17 client = mqtt.Client() 18 client.on_connect = on_connect 19 client.on_message = on_message 20 client.connect('ip', 1883, 600) # ip为消息服务器的ip地址 21 # 600为keepalive的时间间隔 22 while True: 23 msg = input("请输入推送消息:") 24 client.publish('topic', payload=msg, qos=0)
三、写一个订阅客户端 Subscribe.py
1 # __author: gy-chen 2 # data: 2020/5/23 3 # -*- coding: UTF-8 -*- 4 5 import paho.mqtt.client as mqtt 6 7 8 def on_connect(client, userdata, flags, rc): 9 print("Connected with result code: " + str(rc)) 10 11 12 def on_message(client, userdata, msg): 13 topic = msg.topic 14 message = str(msg.payload, encoding="utf-8") 15 print(topic + ":" + message) 16 17 18 client = mqtt.Client() 19 client.on_connect = on_connect 20 client.on_message = on_message 21 # client.on_disconnect = on_disconnect 22 client.connect('ip', 1883, 600) # 600为keepalive的时间间隔 23 client.subscribe('topic', qos=0) 24 client.loop_forever() # 保持连接
例子:
# __author: gy-chen # data: 2020/5/23 # -*- coding: UTF-8 -*- import paho.mqtt.client as mqtt import json import time HOST = "ip" # 消息服务器的ip地址 PORT = 1883 client_id = "1083421xxxxx" # 没有就不写,此处部分内容用xxx代替原内容,下同 def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("data/receive") # 订阅消息 def on_message(client, userdata, msg): print("主题:"+msg.topic+" 消息:"+str(msg.payload.decode('utf-8'))) def on_subscribe(client, userdata, mid, granted_qos): print("On Subscribed: qos = %d" % granted_qos) def on_disconnect(client, userdata, rc): if rc != 0: print("Unexpected disconnection %s" % rc) data = { "type": 2, "timestamp": time.time(), "messageId": "9fcda359-89f5-4933-xxxx", "command": "xx/recommend", "data": { "openId": "xxxx", "appId": 1, "recommendType": "temRecommend" } } param = json.dumps(data) client = mqtt.Client(client_id) client.username_pw_set("xxxxxx", "xxxxxx") client.on_connect = on_connect client.on_message = on_message client.on_subscribe = on_subscribe client.on_disconnect = on_disconnect client.connect(HOST, PORT, 60) client.publish("data/send", payload=param, qos=0) # 发送消息 client.loop_forever()