From 9f99b8a26a19434523c8e4b3358b7c99b915e828 Mon Sep 17 00:00:00 2001 From: fyf <11621@LAPTOP-04QQU0AO> Date: Mon, 12 Jun 2023 11:35:36 +0800 Subject: [PATCH] =?UTF-8?q?=E7=8E=B0=E5=9C=BA=E6=94=B9=E5=8A=A8WWW?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/example/bpa/helper/MQTT.java | 69 ++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/example/bpa/helper/MQTT.java b/app/src/main/java/com/example/bpa/helper/MQTT.java index 5c3d652..dd20ae7 100644 --- a/app/src/main/java/com/example/bpa/helper/MQTT.java +++ b/app/src/main/java/com/example/bpa/helper/MQTT.java @@ -18,6 +18,10 @@ import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.LineNumberReader; + /** * mqtt帮助类 */ @@ -105,9 +109,72 @@ public class MQTT { } }); - ConnMqttBroken(true); + + new Thread(new Runnable() { + @Override + public void run() { + try { + boolean status = false; + while (!status) { + try { + //status为0则代表通,为1则代表不通。 + status =ping2(Ip,1,1); + Thread.sleep(1000); + } catch (InterruptedException e) { + MessageLog.ShowInfo("MQTT " + Ip + " 网络验证失败"); + } catch (Exception e) { + MessageLog.ShowInfo("MQTT " + Ip+ " 网络验证失败"); + } + } + ConnMqttBroken(true); + } catch (Exception e) { + + } + } + }).start(); + } + /** + * Ping PLC地址是否通畅 + * @param address + * @param pingTimes ping的次数 + * @param timeOut 超时时间 10 + * @return + */ + public static boolean ping2(String address, int pingTimes, int timeOut) { + Process process = null; + try { + process = Runtime.getRuntime().exec( "ping " + "-c " + pingTimes + " -w " + timeOut+ " "+address); + InputStreamReader r = new InputStreamReader(process.getInputStream()); + + LineNumberReader returnData = new LineNumberReader(r); + + String returnMsg=""; + + String line = ""; + while ((line = returnData.readLine()) != null) { + + System.out.println(line); + + returnMsg += line; + + } + + if(returnMsg.indexOf("100% packet loss")!=-1){ + System.out.println("与 " +address +" 连接不畅通."); + return false; + } else{ + + System.out.println("与 " +address +" 连接畅通."); + return true; + } + } catch (IOException e) { + e.printStackTrace(); + } + return false; + + } /** * 连接 或者断开MQTT * @param bloConn