Source of GetRemoteTime.java


  1: // GetRemoteTime.java
  2: // Retrieves the time from a "remote" server.

  4: import java.awt.*;
  5: import java.awt.*;
  6: import java.awt.event.*;
  7: import java.net.*;
  8: import java.io.*;

 10: public class GetRemoteTime
 11:     extends Frame
 12:     implements ActionListener
 13: {
 14:     private TextField hostInput;
 15:     private TextArea display;
 16:     private Button button;
 17:     private Button exit;

 19:     public static void main(String [] args)
 20:     {
 21:         GetRemoteTime gr = new GetRemoteTime();
 22:         gr.makeGUI();
 23:         gr.setSize(550, 300);
 24:         gr.setVisible(true);
 25:     }

 27:     public void makeGUI()
 28:     {
 29:         setLayout(new FlowLayout());

 31:         hostInput = new TextField(50);
 32:         add(hostInput);
 33:         button = new Button("Get time from this host");
 34:         add(button);
 35:         display = new
 36:             TextArea("", 0, 0, TextArea.SCROLLBARS_VERTICAL_ONLY);
 37:         add(display);
 38:         button.addActionListener(this);

 40:         exit = new Button("Exit");
 41:         add(exit);
 42:         exit.addActionListener(this);
 43:     }

 45:     public void actionPerformed(ActionEvent event)
 46:     {
 47:         if (event.getSource() == exit)
 48:             System.exit(0);

 50:         String theTime;
 51:         String host = hostInput.getText();

 53:         try
 54:         {
 55:             Socket socket = new Socket(host, 7013);
 56:             //Socket socket = new Socket(host, 13);
 57:             BufferedReader input = new
 58:                 BufferedReader(new
 59:                 InputStreamReader(socket.getInputStream()));
 60:             theTime = input.readLine();
 61:             display.append("The time at " + host +
 62:                            " is " + theTime + ". ");

 64:             socket.close();
 65:         }
 66:         catch (UnknownHostException e)
 67:         {
 68:             display.setText("No such host. ");
 69:         }
 70:         catch (IOException io)
 71:         {
 72:             display.setText(io.toString());
 73:         }
 74:     }
 75: }