package com.whdc.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 Pub { private final String clientId; private final String topic; public static String BROKER; private final int qos; private MqttClient client; public Pub(String clientId, String topic) { this.clientId = clientId; this.topic = topic; this.qos = 0; } public Pub(String clientId, String topic, int qos) { this.clientId = clientId; this.topic = topic; this.qos = qos; } public void connect() throws MqttException { this.client = new MqttClient("tcp://120.24.5.249:3189", "mqttx_2b072a3c", new MemoryPersistence()); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setUserName(Config.USERNAME); connOpts.setPassword(Config.PASSWORD); connOpts.setCleanSession(true); this.client.connect(connOpts); } public void close() { try { this.client.disconnectForcibly(200); this.client.close(true); } catch (MqttException e) { e.printStackTrace(); } } public void pub(String msg) throws MqttException { MqttMessage message = new MqttMessage(msg.getBytes()); message.setQos(qos); this.client.publish(topic, message); } }