Java通过MQTT协议对接第三方设备————够用但不详细
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MqttPublishClient {
private MqttClient mqttClient;
private String broker;
private int qos;
private String topic;
private String userName;
private String password;
public MqttPublishClient(String broker, int qos, String topic, String userName, String password) throws MqttException {
this.broker = broker;
this.qos = qos;
this.topic = topic;
this.userName = userName;
this.password = password;
initializeClient();
}
private void initializeClient() throws MqttException {
String clientId = MqttClient.generateClientId();
mqttClient = new MqttClient(broker, clientId, new MemoryPersistence());
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setUserName(userName);
connOpts.setPassword(password.toCharArray());
mqttClient.connect(connOpts);
}
public void publishMessage(String message) throws MqttException {
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
mqttMessage.setQos(qos);
mqttClient.publish(topic, mqttMessage);
}
public void disconnect() throws MqttException {
if (mqttClient.isConnected()) {
mqttClient.disconnect();
}
}
public static void main(String[] args) {
try {
MqttPublishClient publisher = new MqttPublishClient("tcp://broker.hivemq.com", 2, "test/topic", "user", "pass");
publisher.publishMessage("Hello MQTT");
publisher.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
这段代码展示了如何使用Eclipse Paho客户端库创建一个MQTT客户端,连接到一个MQTT代理,并发布一条消息。这个例子使用了HiveMQ的公共代理,并设置了清理会话和用户认证。在实际应用中,你需要替换代理地址、用户认证信息以及主题名,并根据自己的需求调整服务质量(QoS)。
评论已关闭