자바로 만든 UDP Ping 프로그램이다.
서버를 실행할 때 포트번호를 임의로 적어주면 된다.
예) javac PingServer.java && java PingServer localhost 1024

클라이언트의 실행법은 서버의 IP와 포트번호를 적으면 된다.
예) javac PingClient.java && java PingClient localhost 1024

서버의 코드는 Computer Networking, Kurose and Ross, 5th edition에서 작성된 그대로다.
Programming Assignment 3: UDP Pinger Lab

In this lab, you will study a simple Internet ping server written in the Java language, and implement a corresponding client. The functionality provided by these programs are similar to the standard ping programs available in modern operating systems, except that they use UDP rather than Internet Control Message Protocol (ICMP) to communicate with each other. (Java does not provide a straightforward means to interact with ICMP.)

The ping protocol allows a client machine to send a packet of data to a remote machine, and have the remote machine return the data back to the client unchanged (an action referred to as echoing). Among other uses, the ping protocol allows hosts to determine round-trip times to other machines.
You are given the complete code for the Ping server below. Your job is to write the Ping client.

Server:

// File name: PingClient.java
import java.io.*;
import java.net.*;
import java.util.*;

public class PingServer
{
   private static final double LOSS_RATE = 0.3;
   private static final int AVERAGE_DELAY = 100;  // milliseconds

   public static void main(String[] args) throws Exception
   {
      // Get command line argument.
      if (args.length != 1) {
         System.out.println("Required arguments: port");
         return;
      }
      int port = Integer.parseInt(args[0]);

      // Create random number generator for use in simulating
      // packet loss and network delay.
      Random random = new Random();

      // Create a datagram socket for receiving and sending UDP packets
      // through the port specified on the command line.
      DatagramSocket socket = new DatagramSocket(port);

      // Processing loop.
      while (true) {
         // Create a datagram packet to hold incomming UDP packet.
         DatagramPacket request = new DatagramPacket(new byte[1024], 1024);

         // Block until the host receives a UDP packet.
         socket.receive(request);

         // Print the recieved data.
         printData(request);

         // Decide whether to reply, or simulate packet loss.
         if (random.nextDouble() < LOSS_RATE) {
            System.out.println("   Reply not sent.");
            continue;
         }

         // Simulate network delay.
         Thread.sleep((int) (random.nextDouble() * 2 * AVERAGE_DELAY));

         // Send reply.
         InetAddress clientHost = request.getAddress();
         int clientPort = request.getPort();
         byte[] buf = request.getData();
         DatagramPacket reply = new DatagramPacket(buf, buf.length, clientHost, clientPort);
         socket.send(reply);

         System.out.println("   Reply sent.");
      }
   }

   /*
    * Print ping data to the standard output stream.
    */
   private static void printData(DatagramPacket request) throws Exception
   {
      // Obtain references to the packet's array of bytes.
      byte[] buf = request.getData();

      // Wrap the bytes in a byte array input stream,
      // so that you can read the data as a stream of bytes.
      ByteArrayInputStream bais = new ByteArrayInputStream(buf);

      // Wrap the byte array output stream in an input stream reader,
      // so you can read the data as a stream of characters.
      InputStreamReader isr = new InputStreamReader(bais);

      // Wrap the input stream reader in a bufferred reader,
      // so you can read the character data a line at a time.
      // (A line is a sequence of chars terminated by any combination of \r and \n.)
      BufferedReader br = new BufferedReader(isr);

      // The message data is contained in a single line, so read this line.
      String line = br.readLine();

      // Print host address and data received from it.
      System.out.println(
         "Received from " +
         request.getAddress().getHostAddress() +
         ": " +
         new String(line) );
   }
}

Client:

// File name: PingClient.java
import java.util.*;
import java.net.*;
import java.text.*;

public class PingClient
{
    private static final int PING_MESSAGES = 10;
    private static final int TOKEN_TIMESTAMP = 2;
    private static final int MAX_WAIT_TIME = 1000;
    private static final String CRLF = "\r\n";

    public static void main(String[] args) throws Exception
    {
        // If user doesn't input both port number and ip address, the program will display an error message.
        if (args.length != 2)
        {
            System.out.println("usage: java PingClient <Host> <Port>");
            //return;
        }
        
        try
        {
            if(!args[0].isEmpty())
                System.out.println("\nHost: "+args[1]+"\nIP address: "+args[0]+"\n");
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Host name and ip address please");
            System.exit(1);
        }
        InetAddress host = InetAddress.getByName(args[0]);
        
        int portNumber = Integer.parseInt(args[1]);
        
        //Create a datagram socket used for sending and recieving UDP packets
        DatagramSocket socket = new DatagramSocket();

        //Set up the maximum time the socket waits for responses
        socket.setSoTimeout(MAX_WAIT_TIME);

        //Construct a ping message to be sent to the Server
        for (int sequence_num = 0; sequence_num < PING_MESSAGES; sequence_num++)
        {
                String message = generatePing(sequence_num);
                DatagramPacket ping_request =
                    new DatagramPacket(message.getBytes(), message.length(), host, portNumber);

                //Send a ping request
                socket.send(ping_request);

                //Datagram packet to hold server response
                DatagramPacket ping_response =
                    new DatagramPacket(new byte[message.length()], message.length());

                //Wait for ping response from server
                try
                {
                        socket.receive(ping_response);
                        printData(ping_response);
                }
                catch (SocketTimeoutException e)
                {
                        System.out.println("No response was received from the server");
                }
                catch (Exception e)
                {
                        //Another unknown error may have occured that can't be handled
                        e.printStackTrace();
                        return;
                }
        }
    }

    private static String generatePing(int sequence_num)
    {
        // For getting current date and time 
        SimpleDateFormat sdfNow = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        String strNow = sdfNow.format(new Date(System.currentTimeMillis()));
        return "PING #" + sequence_num + " " + System.currentTimeMillis() + " ("+strNow+")";
    }

    //Print ping page to standard output stream
    private static void printData(DatagramPacket request) throws Exception
    {
        String response = new String(request.getData());
        String[] tokens = response.split(" ");
        
        //Create sent and received timestamps for RTT
        long sent_timestamp = new Long(tokens[TOKEN_TIMESTAMP]);
        long received_timestamp = System.currentTimeMillis();

        //RTT
        long rtt = received_timestamp - sent_timestamp;

        //Display results
        System.out.print(response+" Received from "+
                request.getAddress().getHostAddress() + " "+"(RTT=" + rtt + "ms)"+CRLF);
    }
}