ตัวอย่างด้านล่างเป็นการเขียนโปรแกรมภาษาจาวาเพื่อรอรับข้อมูลที่ส่งมาจากอุปกรณ์ IoT โดยใช้ไลบรารี่ Eclipse Paho MQTT client เพื่อสร้างตัวเองให้เป็นลูกข่าย (client ) ของเครือข่าย MQTT และเชื่อมต่อไปยังจุดที่เก็บข้อมูลที่ส่งมาจากอุปกรณ์ IoT เมื่อได้รับข้อมูลมาแล้วจะใช้เมธอด messageArrived ของคลาสแบบอินเตอร์เฟส MqttCallback เพื่อจัดการกับข้อมูล ไลบรารี่ Eclipse Paho MQTT client สามารถดาวน์โหลดได้จาก https://www.eclipse.org/paho/clients/java/
import org.eclipse.paho.client.mqttv3.*;
public class IoTSubscriber implements MqttCallback {
private MqttClient client;
public IoTSubscriber() {
try {
// Create a new MQTT client with a unique client ID
String clientId = MqttClient.generateClientId();
client = new MqttClient("tcp://iot.eclipse.org:1883", clientId);
// Set the callback object for handling incoming messages
client.setCallback(this);
// Connect to the MQTT broker
client.connect();
// Subscribe to the topic that the IoT device is publishing data to
String topic = "iot/device/data";
client.subscribe(topic);
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void connectionLost(Throwable cause) {
// Reconnect to the MQTT broker if the connection is lost
System.out.println("Connection lost!");
try {
client.reconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
// Handle the incoming message from the IoT device
System.out.println("Received message: " + message.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// Not used in this example
}
public static void main(String[] args) {
// Create a new instance of the IoTSubscriber class
IoTSubscriber subscriber = new IoTSubscriber();
}
}