我正在尝试构建一个接收位置的纬度和经度的简单应用程序,然后返回该位置的地址。该应用程序有2部分:Android应用程序和Analytic应用程序。客户端的Android应用程序将向CloudMQTT发送纬度和长度,Analytic应用程序将从CloudMQTT接收纬度和长度,分析然后将结果发送到客户端的Android应用程序VIA TCP。但问题是,当我将runResultTCPAnalytic函数(通过TCP将分析应用程序的结果发送到客户端的函数)添加到run函数时,会出现MQTT连接丢失ERROR。但是当我排除sendResult函数并且只显示云上的内容时,连接运行正常。可以有人向我解释。谢谢。抱歉我的英语不好,我不是母语人士。 这是我的MQTT代码:
public void run() {
try {
mqttClient = new MqttClient(broker, "AnalyticApp");
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(false);
connOpts.setUserName(username);
connOpts.setPassword(password.toCharArray());
noticeBoard.append("Connecting to " + broker + "\n");
String topic = "Assignment";
mqttClient.setCallback(new MqttCallback() {
public void messageArrived(String topic, MqttMessage message) throws Exception {
String data = new String(message.getPayload());
String[] field = data.split(",");
boolean isDuplicate = false;
Device newDevice = new Device(field);
for (int index = 0; index < devices.size(); index++) {
if (devices.get(index).id.equals(field[0])) {
isDuplicate = true;
devices.remove(index);
devices.add(index, newDevice);
}
}
if (!isDuplicate || devices.isEmpty()) {
devices.add(newDevice);
}
noticeBoard.append(" " + "\n");
noticeBoard.setText("");
for (int index=0;index<devices.size();index++) {
do {
GeoCoding temp=new GeoCoding();
devices.get(index).resultaddress=temp.getAddress(devices.get(index).latitude+","+devices.get(index).longitude);
}while(devices.get(index).resultaddress==null);
}
for (int index = 0; index < devices.size(); index++) {
noticeBoard.append(devices.get(index).id + "\t"
+ devices.get(index).longitude + "\t"
+ devices.get(index).latitude + "\t"
+ devices.get(index).portTCP + "\t"
+devices.get(index).resultaddress+"\n"
);
sendResultTCPAnalytic(devices.get(0).id, 3333, devices.get(0).resultaddress);
}
}
public void connectionLost(Throwable cause) {
noticeBoard.append("Connection to broker lost!" + cause.getMessage() + "\n");
}
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
while (true) {
mqttClient.connect(connOpts);
mqttClient.subscribe(topic, 1);
}
} catch (MqttException me) {
noticeBoard.append(me.getMessage() + "\n");
}
}
这是我的sendResultTCPAnalytic代码:
public void sendResultTCPAnalyticServer(String host, int port,String result) throws Exception
{
Socket socketOfClient;
try
{
socketOfClient = new Socket(host, port); /*CREATE SOCKET*/
OutputStream os = socketOfClient.getOutputStream();
try
{
String dataToSend = null;
if ((result) != null)
{
dataToSend = result;
os.write(dataToSend.getBytes());
} else
{
socketOfClient.close();
}
socketOfClient.close();
} catch (IOException e)
{
e.printStackTrace();
}
} catch (UnknownHostException e)
{
e.printStackTrace();
}
}
这是错误:
Connection to broker lost!MQTT Exception