给我展示Eclipse Paho 提供的 MQTT Java 示例代码
时间: 2023-05-23 11:01:53 浏览: 296
当然,我可以展示Paho MQTT Java的示例代码。下面是使用Eclipse Paho实现MQTT的Java示例代码:
import org.eclipse.paho.client.mqttv3.*;
public class MqttClientDemo {
public static void main(String[] args) throws MqttException, InterruptedException {
String broker ="tcp://localhost:1883";
String clientId = MqttClient.generateClientId();
MqttClient client = new MqttClient(broker, clientId);
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setUserName("username");
connectOptions.setPassword("password".toCharArray());
client.connect(connectOptions);
String topic = "test";
int qos = 1;
client.subscribe(topic, qos);
String content = "Hello MQTT";
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
client.publish(topic, message);
Thread.sleep(1000);
client.disconnect();
}
}
我希望这个简单的MQTT示例能够帮助你开始使用Eclipse Paho。
阅读全文