1、添加必要的注釋:對(duì)于復(fù)雜的代碼塊,如subscribeAndReceiveMessages
方法,建議添加詳細(xì)的注釋以解釋其功能。
2、更新依賴信息:確保使用的版本號(hào)是最新的,以便獲得最佳兼容性和性能。
3、代碼復(fù)用:對(duì)于重復(fù)出現(xiàn)的部分,考慮將其封裝成單獨(dú)的方法或類,減少冗余代碼。
以下是改進(jìn)后的代碼示例:
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!"); } /** * 發(fā)送消息到指定主題 * @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); // 檢查訂閱狀態(tài) if (!token.isCompleted()) { continue; // 如果沒有完成,繼續(xù)等待 } MqttMessage receivedMsg = token.getPayload(); System.out.println("Received message from topic: " + receivedMsg.getTopic() + ", with payload: " + new String(receivedMsg.getPayload())); break; // 停止循環(huán),接收下一個(gè)消息 } 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(); } } }
這段代碼已經(jīng)包含了必要的注釋,并且使用了最新的版本號(hào),它還提供了完整的生命周期管理,包括連接到MQTT代理、發(fā)送消息以及訂閱并接收消息,這樣可以幫助讀者更好地理解和維護(hù)代碼。