FileDocCategorySizeDatePackage
TimeServer.javaAPI DocExample2042Thu Feb 16 12:01:48 GMT 2006None

TimeServer

public class TimeServer extends MIDlet

Fields Summary
Constructors Summary
Methods Summary
protected voiddestroyApp(boolean unconditional)

private byte[]getTime()

      
    byte[] result = new byte[4];
    Date now = new Date();
      
    // The time protocol uses an unsigned 4-byte int so we have
    // to do all the arithmetic with longs and then extract the
    // four low-order bytes
    long secondsSince1970 = now.getTime()/1000;
    long differenceBetweenEpochs = 2208988800L;
    long secondsSince1900 = differenceBetweenEpochs + secondsSince1970;
    result[0] = (byte) ((secondsSince1900 & 0xFF000000) >>> 24);
    result[1] = (byte) ((secondsSince1900 & 0xFF0000) >>> 16);
    result[2] = (byte) ((secondsSince1900 & 0xFF00) >>> 8);
    result[3] = (byte) (secondsSince1900 & 0xFF);
  
    return result;
  
protected voidpauseApp()

protected voidstartApp()

    
     DatagramConnection connection;
     try {
       connection = (DatagramConnection) Connector.open("datagram://:37");
       Datagram incoming = connection.newDatagram(128);
       Datagram response = connection.newDatagram(4);
       while (true) {
         try {
           connection.receive(incoming);
           response.reset();
           response.setAddress(incoming);
           response.setData(getTime(), 0, 4);
           connection.send(response);
           incoming.reset();
         }
         catch (IOException ex) {
           // As long as it's just an error on this one connection
           // we can ignore it
         }
      }     
    }
    catch (IOException ex) {
      // If we can't open the channel, put up an Alert
      Alert alert = new Alert("UDP Error");
      alert.setTimeout(Alert.FOREVER);
      alert.setString("Could not connect to port 37. Needs root privileges?");
      Display.getDisplay(this).setCurrent(alert);
    }