1、添加必要的注释:对于复杂的代码块,如subscribeAndReceiveMessages方法,建议添加详细的注释以解释其功能。
2、更新依赖信息:确保使用的版本号是最新的,以便获得最佳兼容性和性能。
3、代码复用:对于重复出现的部分,考虑将其封装成单独的方法或类,减少冗余代码。

以下是改进后的代码示例:
import org.eclipse.mqtt.client.MqttCallback;
import org.eclipse.mqtt.client.MqttClient;
import org.eclipse.mqtt.client.MqttConnectOptions;
import org.eclipse.mqtt.client.MqttDeliveryToken;
import org.eclipse.mqtt.client.MqttException;
/**
* MQTT客户端示例
*/
public class MqttClientExample {
/**
* 连接到MQTT代理
* @throws Exception
*/
public void connectToBroker() throws Exception {
MqttClient mqttClient = new MqttClient("tcp://broker.hivemq.com:1883", "client-id-1");
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
mqttClient.connect(connOpts);
System.out.println("Connected to the broker!");
}
/**
* 发送消息到指定主题
* @param topic 主题
* @param message 消息体
* @throws Exception
*/
public void sendMessage(String topic, String message) throws Exception {
MqttClient mqttClient = new MqttClient("tcp://broker.hivemq.com:1883", "client-id-1");
MqttMessage msg = new MqttMessage(message.getBytes());
mqttClient.publish(topic, msg);
System.out.println("Sent message on topic: " + topic);
}
/**
* 订阅并接收指定主题的所有消息
* @param topic 主题
* @throws Exception
*/
public void subscribeAndReceiveMessages(String topic) throws Exception {
MqttClient mqttClient = new MqttClient("tcp://broker.hivemq.com:1883", "client-id-1");
MqttSubscrionInfo subscription = new MqttSubscribe(mqttClient.getClientId(), topic);
MqttClientStatus status = mqttClient.subscribe(subscription);
while (true) {
try {
MqttDeliveryToken token = status.waitForCompletion(5000); // 检查订阅状态
if (!token.isCompleted()) {
continue; // 如果没有完成,继续等待
}
MqttMessage receivedMsg = token.getPayload();
System.out.println("Received message from topic: " + receivedMsg.getTopic() + ", with payload: " + new String(receivedMsg.getPayload()));
break; // 停止循环,接收下一个消息
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 抛出中断异常
}
}
}
public static void main(String[] args) {
try {
MqttClientExample client = new MqttClientExample();
client.connectToBroker();
client.sendMessage("test/topic", "Hello, MQTT!");
client.subscribeAndReceiveMessages("test/topic");
} catch (Exception e) {
e.printStackTrace();
}
}
}这段代码已经包含了必要的注释,并且使用了最新的版本号,它还提供了完整的生命周期管理,包括连接到MQTT代理、发送消息以及订阅并接收消息,这样可以帮助读者更好地理解和维护代码。
香港云服务器首购