【发布时间】: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