FileDocCategorySizeDatePackage
TimeServer.javaAPI DocExample1894Sat Sep 09 20:50:40 BST 2000None

TimeServer

public class TimeServer extends Object

Fields Summary
public static final int
DEFAULT_PORT
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)


       
        
   int port = DEFAULT_PORT;     
   if (args.length > 0) {
     try {
        port = Integer.parseInt(args[0]);
        if (port < 0 || port >= 65536) {
          System.out.println("Port must between 0 and 65535");
          return;      
        }
     }   
     catch (NumberFormatException e) {}  
   }     

   // The time protocol sets the epoch at 1900,
   // the java Date class at 1970. This number 
   // converts between them.
    
   long differenceBetweenEpochs = 2208988800L;
    
   try {
     ServerSocket server = new ServerSocket(port);
       while (true) {
         Socket connection = null;
         try {
           connection = server.accept();
           OutputStream out = connection.getOutputStream();
           Date now = new Date();
           long msSince1970 = now.getTime();
           long secondsSince1970 = msSince1970/1000;
           long secondsSince1900 = secondsSince1970 
            + differenceBetweenEpochs;
           byte[] time = new byte[4];
           time[0] 
            = (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24);
           time[1] 
            = (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
           time[2] 
            = (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
           time[3] = (byte) (secondsSince1900 & 0x00000000000000FFL);
           out.write(time);
           out.flush();      
         } // end try
         catch (IOException e) {
         } // end catch
         finally {
           if (connection != null) connection.close(); 
         }
       }  // end while
   }  // end try
   catch (IOException e) {
     System.err.println(e);
   } // end catch