MQTT协议
MQTT客户端
MQTT客户端MQTTClient,采用主题订阅方式实现消息收发的机制。
private int qos1 = 2;
private List<String> msgList = new ArrayList<String>();
public void MessageQueue () {
threadFlag = true;
//构造MQTT客户端
MQTTClient mqttAndroidClient1 = new MQTTClient();
MQTTClient mqttAndroidClient2 = new MQTTClient();
//创建连接
mqttAndroidClient1.create("182.92.150.115","supermap","supermap123", clientID[0]);
mqttAndroidClient2.create("182.92.150.115","supermap","supermap123", clientID[1]);
//订阅主题
mqttAndroidClient1.subscribe(topicName, qos1);
//接收消息
thread = new Thread(new Runnable() {
@Override
public void run() {
while (threadFlag) {
//接收消息
String expReceive1 = revMessage(mqttAndroidClient1);
if (!expReceive1.isEmpty()) {
msgList.add(expReceive1);
}
}
}
});
thread.start();
//发送消息
mqttAndroidClient2.sendMessage(topicName, sMessage);
}
//接收消息
private String revMessage(MQTTClient mqttClient) {
mqReturnMessage = mqttClient.receiveMessage();
String receiveMsg = mqReturnMessage.getMessage();
return receiveMsg;
}