import random
import paho.mqtt.client as mqtt
import paho.mqtt.publish as mqttpublish
import time, threading
HOST = "127.0.0.1"
PORT = 1883
TOPIC = "/test/sx789"
USER, PASSWORD = "", ""
def connect_mqtt():
client_id = f"C{int(time.time() * 1000)}_{random.randint(0, 1000)}"
client = mqtt.Client(client_id)
if USER:
client.username_pw_set(USER, PASSWORD)
client.connect(HOST, PORT, 60)
return client
def client_sub():
def on_connect(client, userdata, flags, rc):
if rc:
print("Connected ERROR with code " + str(rc))
client.subscribe(TOPIC)
def on_message(client, userdata, msg):
print("Received " + msg.topic + " " + msg.payload.decode("utf-8"))
client = connect_mqtt()
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
def publish(client, msg):
result = client.publish(TOPIC, msg, qos=1, retain=False)
if result[0]:
print(f"Failed to send message to topic {TOPIC}")
else:
pass
def sendmsg(msg):
mqttpublish.single(
TOPIC,
msg,
qos=1,
hostname=HOST,
port=PORT,
client_id=f"temp{random.randint(0, 1000)}",
auth={"username": USER, "password": PASSWORD} if USER else {},
)
if __name__ == "__main__":
for i in range(1, 15):
threading.Timer(
1 + i * 0.1,
sendmsg,
(f"你好,MQTT! {i} {time.strftime('%Y%m%d_%H%M%S', time.localtime())}",),
).start()
s = connect_mqtt()
for i in range(1, 15):
threading.Timer(1 + i * 0.1, publish, (s, f"传输:{i}")).start()
t = threading.Thread(target=client_sub)
t.daemon = True
t.start()
print("ok")