dcsimg
December 3, 2020
Hot Topics:

Java Internet Programming: Level 2

  • By Thornton Rose
  • Send Email »
  • More Articles »

  daytime.java
(Code Sample)

 

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * This class is a simple client that uses the Daytime internet protocol to get
 * the date & time from a given host.
 */
public class Daytime {

   // main()
   //
   public static void main(String[] args) {
      String         host;
      InetAddress    hostAddress;
      String         inBuffer;
      Socket         daytimeSocket;
      BufferedReader socketIn;

      // If number of args < 1, print usage.

      if (args.length < 1) {
         System.out.println("Usage: Daytime <host>");

      } else {

         try {
            // Get the host.

            host = args[0];
            hostAddress = InetAddress.getByName(host);

            System.out.println("Connecting to " + hostAddress.toString() + " ...");

            // Open a socket on port 13.

            daytimeSocket = new Socket(hostAddress, 13);

            // Send the requests and read the replies.

            try {
               // Set the socket timeout to 5 seconds.

               daytimeSocket.setSoTimeout(5 * 1000);

               // Get the I/O streams.

               socketIn = new BufferedReader(
                  new InputStreamReader(daytimeSocket.getInputStream()));

               // Read the reply from the server.

               inBuffer = socketIn.readLine();
               System.out.println("Reply received: " + inBuffer);

            } finally {
               // Close the socket.
               
               daytimeSocket.close();
            }

         // If there is an exception, print it.

         } catch(Exception ex) {
            System.out.println(ex);
         }
      }

      System.exit(0);
   }
}









Page 2 of 2



This article was originally published on November 16, 1999

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.


Thanks for your registration, follow us on our social networks to keep up-to-date