1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MyMqttClient {
public static void main(String[] args) { Client(); }
public static void Client(){
String MQTT_HOST = "tcp://10.245.228.67:1883"; String MQTT_CLIENT_ID = "client1"; String userName = "admin"; String password = "password"; String MQTT_TOPIC = "this is my first topic";
MqttClient client = null; try { client = new MqttClient(MQTT_HOST, MQTT_CLIENT_ID, new MemoryPersistence()); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(true); options.setUserName(userName); options.setPassword(password.toCharArray()); options.setConnectionTimeout(10); options.setKeepAliveInterval(20); client.connect(options); } catch (MqttException e) { e.printStackTrace(); }
try { client.subscribe(MQTT_TOPIC); client.setCallback(new MqttCallback() {
@Override public void connectionLost(Throwable cause) { System.out.println("连接失去了"); }
@Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println("接受消息成功,topic:"+topic+" 内容:"+message); }
@Override public void deliveryComplete(IMqttDeliveryToken token) {
} }); } catch (MqttException e) { e.printStackTrace(); } }
}
|