我有一个问题-
声明:我将从客户端向服务器发送数据,服务器收到客户端的消息后将向客户端返回一些数据。将发送到服务器的数据将以一定的频率发送,如果我在一定的超时时间内没有收到服务器的回复,我应该在客户端中显示“服务器是无状态的并且不工作”。
以下是我的代码和问题:
package com.soc;
import java.io.*;
import java.net.*;
import java.util.Timer;
import java.util.TimerTask;
public class LocalFaultDetector {
public static void main(String[] args) throws UnknownHostException, IOException {
Timer timer = new Timer();
int heartbeatFreq = 3000; // Configure your default frequency in milliseconds
String serverIP = "localhost"; // Replace with the IP address of your server
int serverPort = 8999; // Replace with the port your server is listening on
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try(Socket socket = new Socket(serverIP, serverPort)) {
// Send the message to Server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Message from client to the server");
// Print sending message on LFD1 console
System.out.println("Sent message to server with the message");
// Set a timeout for reading the response
socket.setSoTimeout(timeout);
//IF THE TIMEOUT IS CROSSED, HOW DO I EXIT THE scheduleAtFixedRate loop.
// Read the response from the server
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String serverResponse = in.readLine();
if(serverResponse != null){
System.out.println("Received response from server: " + serverResponse);
} else {
System.err.println("No response received from the server within the timeout.");
}
} catch (SocketTimeoutException e) {
System.err.println("Timeout waiting for a response from the server.");
} catch (IOException e) {
// Handle exceptions (e.g., server not responding)
System.err.println("Error: " + e.getMessage());
}
}
}, 0, heartbeatFreq);
}
}
我的问题:
如果
socket.setSoTimeout(timeout);
超时,如何退出/中断/关闭/取消scheduleAtFixedRate
,让客户端不再向服务器发送消息?
是否有其他最佳方法可以按频率(即每 5 秒)将消息从客户端发送到服务器,并等待服务器的回复并检查是否从服务器返回消息。任何建议都会有帮助。
我已经尽力了,而且我对网络编程还很陌生。以上是我尝试过的代码。
TimerTask
有一个cancel
方法
取消该定时任务。如果任务已经被调度为一次性执行但尚未运行,或者尚未被调度,则永远不会运行。如果该任务已被安排重复执行,则它将永远不会再次运行。 (如果发生此调用时任务正在运行,则任务将运行至完成,但永远不会再次运行。)
这样您可以在发生 SocketTimeoutException 时取消任务。
catch (SocketTimeoutException e) {
System.err.println("Timeout waiting for a response from the server.");
cancel();
}
还有另一种方式来实现定时任务,可以实现更复杂的功能,对于简单的任务,
Timer
就够了。
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(() -> {
try {
} catch (Exception e) {
executor.shutdown();
}
}, 0, 5, TimeUnit.SECONDS);