client2.java
2.33 KB
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
68
69
70
71
72
package com.huaheng.framework.mqtt;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class client2 {
//连接地址
public static final String HOST = "tcp://47.100.176.190:1883";
//订阅的话题
public static final String TOPIC = "18761185821onlineInform";
//客户端ID 全球唯一,建议使用UUID生成
private static final String clientid = "client124";
private MqttClient client;
private MqttConnectOptions options;
private String userName = "admin";
private String passWord = "admin";
public void start() {
try {
// MemoryPersistence设置clientid的保存形式,默认为以内存保存
client=new MqttClient(HOST, clientid,new MemoryPersistence());
//连接设置
options=new MqttConnectOptions();
//清除会话
options.setCleanSession(false);
//用户名密码 密码类型是char数组
options.setUserName(userName);
options.setPassword(passWord.toCharArray());
//超时时间
options.setConnectionTimeout(10);
//心跳
options.setKeepAliveInterval(20);
//设置回调
client.setCallback(mqttCallback);
//主题类
MqttTopic topic=client.getTopic(TOPIC);
//遗嘱设置
options.setWill(topic, "close".getBytes(), 2, true);
client.connect(options);
//订阅主题 qos为订阅主题的下标的消息服务质量
int[] Qos = {1};
String[] topic1 = {TOPIC};
client.subscribe(topic1, Qos);
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
client2 client2=new client2();
client2.start();
}
MqttCallback mqttCallback = new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
};
}