python----搞MQTT

首先参见这个文章:https://blog.csdn.net/qq_43030934/article/details/107638059
MQTT消息订阅.py

import paho.mqtt.client as mqtt

# 连接成功回调
def on_connect(client, userdata, flags, rc):
    print('Connected with result code '+str(rc))
    client.subscribe('testtopic/#')

# 消息接收回调
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()

# 指定回调函数
client.on_connect = on_connect
client.on_message = on_message

# 建立连接
client.connect('broker.emqx.io', 1883, 60)

# 发布消息
client.publish('emqtt',payload='Hello World',qos=0)

client.loop_forever()

MQTT消息发布.py

import paho.mqtt.client as mqtt

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

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect('127.0.0.1', 1883, 600) # 600为keepalive的时间间隔
client.publish('fifa', payload='amazing', qos=0)

订阅保持长连接监听消息.py

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import json
import time

HOST = "127.0.0.1"
PORT = 1883
# client_id = ""                       # 没有就不写,此处部分内容用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":'xxxx',
        "recommendType":"temRecommend"
    }
}
param = json.dumps(data)
client = mqtt.Client()
client.username_pw_set("user")
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()

要学会对EMQ的运用,在EMQ里也有发送MQTT的工具
python----搞MQTT_第1张图片
监控报文,要下载这个npcap,参见:
https://blog.csdn.net/taoshihan/article/details/106954228
在这里插入图片描述
python----搞MQTT_第2张图片
出现这个图标才能监控回环报文

你可能感兴趣的:(笔记,网络安全,python,safari)