【问题标题】:How to continue infinite while loop even after exception即使在异常之后如何继续无限循环
【发布时间】:2021-05-01 21:26:54
【问题描述】:

我编写了一段代码通过 TCP 将数据发送到服务器,但服务器可能并不总是启动。所以我想我可以让发送者在无限循环中以 10 秒的间隔尝试传输数据。但问题是当服务器没有启动时,发送方会出现异常,这是意料之中的。我尝试使用 try 和 catch 处理异常,以便循环可以继续,即使它们发生但我不能,并且在异常发生之后,循环中断并且在下一个时间间隔内没有任何反应。

我怎样才能写出这样的程序(即使发生异常也可以继续循环)?

PS。通过调用循环并向其发送两个值来初始化程序。

public void loop(String serverIP, String GSID)  {

    while (true) {

        try {
            dataTransmission(serverIP, GSID);
            TimeUnit.SECONDS.sleep(10);

        } catch (InterruptedException e) {
            System.out.println(e);
        }
    }
}

public void dataTransmission(String GSID,String serverIP ) {


    System.out.println("GS ID=" + GSID);
    System.out.println("server IP=" + serverIP);


    Socket s1 = null;
    BufferedReader br = null;
    BufferedReader is = null;
    PrintWriter pwr = null;
    String response = null;


    String ServerIP = "localhost";


    try {
        s1 = new Socket(ServerIP, 4445);
        br = new BufferedReader(new InputStreamReader(System.in));
        is = new BufferedReader(new InputStreamReader(s1.getInputStream()));
        pwr = new PrintWriter(s1.getOutputStream());

    } catch (IOException e) {
        System.out.println(e);
    }



    // send GSID to Server
    pwr.println(GSID);
    pwr.flush();


    // get GS IP
    String GSIP = null;
    try {
        GetGasStationIP gsip = new GetGasStationIP();
        GSIP = gsip.getSourceIP();

    } catch (UnknownHostException e) {
        System.out.println(e);
    }


    // send GSIP to Server
    pwr.println(GSIP);
    pwr.flush();
    //response = is.readLine();
    //System.out.println("Server Response : " + response);


    // send time
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime now = LocalDateTime.now();
    pwr.println(dtf.format(now));
    pwr.flush();
    //response = is.readLine();
    //System.out.println("Server Response : " + response);


    try {
        is.close();
        pwr.close();
        br.close();
        s1.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("Connection Closed");
    System.out.println("");
}

}

【问题讨论】:

  • 我不知道我是否理解你的问题,但为什么不在 catch 块中使用“继续”?
  • 我猜除了InterruptedException 之外还有其他一些异常发生。您可以尝试在 loop 方法中捕获所有 Exception 而不仅仅是 InterruptedException。这可能会对您有所帮助。
  • @Nils continue 不会在这里做任何事情吗?捕获后没有代码,所以无论如何它都会继续。

标签: java loops exception while-loop tcp


【解决方案1】:

您的代码很可能会引发您未处理的运行时异常。

尝试在 while 循环中捕获 Exception 而不是 InterruptedException(尽管不推荐)。

您需要捕获服务器关闭时发生的确切运行时异常并进行处理。

【讨论】:

    猜你喜欢
    • 2018-03-20
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2020-07-01
    • 2015-08-19
    • 1970-01-01
    相关资源
    最近更新 更多