python代码
# python3.6importrandomfrompaho.mqttimportclientasmqtt_clientbroker='ip'# 与Publish一样port=1883# 与Publish一样topic="test"# 准备订阅该Topic# generate client ID with pub prefix randomlyclient_id=f'python-mqtt-{random.randint(0, 100)}'# 生成一个设备号# 与小节3一直,都是连接到Borkerdefconnect_mqtt(): defon_connect(client, userdata, flags, rc): ifrc==0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client=mqtt_client.Client(client_id) client.on_connect=on_connectclient.connect(broker, port) returnclient# 订阅函数,设定要订阅的Topic,以及设定接受信息后的回调函数defsubscribe(client): defon_message(client, userdata, msg): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") client.subscribe(topic) client.on_message=on_messageif__name__=='__main__': client=connect_mqtt()# 连接subscribe(client) # 订阅设置# 网络阻塞,不断接受并调用回调函数处理结果,意味着代码会一直卡在这里接受,所以可以使用多线程来使用client.loop_forever()