代码实现如下:
PingServer.java
import java.io.;
import java.net.;
import java.util.Random;
public class PingServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java PingServer ");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
System.out.println("PingServer is running on port " + portNumber + "...");
while (true) {
Socket clientSocket = serverSocket.accept();
new PingServerThread(clientSocket).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + portNumber);
System.exit(-1);
}
}
}
class PingServerThread extends Thread {
private final Socket clientSocket;
private final Random random;
private final int LOSS_RATE = 50; // percentage of packets lost
private final int DELAY = 100; // milliseconds delay for RTT
public PingServerThread(Socket socket) {
this.clientSocket = socket;
this.random = new Random();
}
public void run() {
try (
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
) {
System.out.println("New client connected.");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Message received from client: " + inputLine);
if (random.nextInt(100) < LOSS_RATE) {
System.out.println("Packet lost.");
continue;
}
Thread.sleep(random.nextInt(DELAY * 2));
out.println("Echo: " + inputLine);
}
System.out.println("Client disconnected.");
clientSocket.close();
} catch (IOException e) {
System.err.println("Error handling client.");
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
PingClient.java
import java.io.;
import java.net.;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PingClient {
private static final int TIMEOUT = 1000; // milliseconds
private static final int NUM_REQUESTS = 10;
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Usage: java PingClient <hostname> <port number>");
System.exit(1);
}
String hostname = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket pingSocket = new Socket(hostname, portNumber);
PrintWriter out = new PrintWriter(pingSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(pingSocket.getInputStream()))
) {
System.out.println("Connected to PingServer at " + hostname + ":" + portNumber + ".");
long minRTT = Long.MAX_VALUE;
long maxRTT = Long.MIN_VALUE;
long totalRTT = 0;
for (int i = 0; i < NUM_REQUESTS; i++) {
String message = "PingUDP " + i + " " + getTimeStamp() + " CRLF";
out.println(message);
long startTime = System.currentTimeMillis();
pingSocket.setSoTimeout(TIMEOUT);
try {
String response = in.readLine();
long endTime = System.currentTimeMillis();
long rtt = endTime - startTime;
System.out.println("Response from server: " + response);
System.out.println("Round-trip time: " + rtt + "ms");
if (rtt < minRTT) {
minRTT = rtt;
}
if (rtt > maxRTT) {
maxRTT = rtt;
}
totalRTT += rtt;
} catch (SocketTimeoutException e) {
System.out.println("Request timed out.");
}
Thread.sleep(1000);
}
double avgRTT = (double) totalRTT / NUM_REQUESTS;
System.out.println("-----------------------------");
System.out.println("Minimum RTT: " + minRTT + "ms");
System.out.println("Maximum RTT: " + maxRTT + "ms");
System.out.println("Average RTT: " + String.format("%.2f", avgRTT) + "ms");
} catch (UnknownHostException e) {
System.err.println("Unknown host " + hostname);
System.exit(-1);
} catch (IOException e) {
System.err.println("Error connecting to " + hostname);
System.exit(-1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static String getTimeStamp() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return format.format(new Date());
}
}