home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / code / ch10.txt < prev    next >
Text File  |  1998-12-14  |  23KB  |  1,027 lines

  1. WriteStream.java:
  2.  
  3. import java.io.*;
  4.  
  5. public class WriteStream
  6. {
  7.     // This program runs as an application
  8.     public static void main(String[] arguments)
  9.     {
  10.         //Create an array of data to print
  11.         int[] allBytes = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};
  12. try
  13.         {
  14.             //declare a stream
  15.             FileOutputStream ofile = new σFileOutputStream("bytes.dat");
  16. for (int i=0; i < allBytes.length; i++)
  17.                 //write to the stream
  18.                 ofile.write(allBytes[i]);
  19.             ofile.close();
  20.         } catch (IOException e)// handle any errors
  21.             {
  22.                 System.out.println("Error - " + e.toString());
  23.             }//catch
  24.     }//main
  25. }//WriteStream
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32. ReadStream.java:
  33.  
  34. import java.io.*;
  35.  
  36. public class ReadStream
  37. {
  38.     // This program runs as an application
  39.     public static void main(String[] arguments)
  40.     {
  41.         try
  42.         {
  43.             //declare a stream
  44.             FileInputStream ifile = new FileInputStream("bytes.dat");
  45. boolean eof = false;
  46.             int cntBytes = 0;
  47.             while (!eof)
  48.             {
  49.                int thisVal = ifile.read();
  50.                System.out.print( thisVal + " ");
  51.                if (thisVal == -1)
  52.                   eof = true;
  53.                else
  54.                   cntBytes++;
  55.             } //while
  56.             ifile.close();
  57.             System.out.print("\nBytes read: " + cntBytes);
  58.  
  59.        } catch (IOException e)// handle any errors
  60.             {
  61.                 System.out.println("Error - " + e.toString());
  62.             }//catch
  63.     }//main
  64. }//ReadStream
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71. BufferedWriteStream.java:
  72.  
  73. import java.io.*;
  74.  
  75. public class BufferedWriteStream
  76. {
  77.     // This program runs as an application
  78.     public static void main(String[] arguments)
  79.     {
  80.         //Create an array of data to print
  81.         int[] allBytes = {1,3,5,7,9,11,13,15,17,19,21,23,25,27,29};
  82. try
  83.         {
  84.             //declare a stream
  85.             FileOutputStream ofile = new FileOutputStream("bufBytes.dat");
  86. BufferedOutputStream bufStream = new BufferedOutputStream(ofile);
  87. for (int i=0; i < allBytes.length; i++)
  88.                 //write to the stream
  89.                 bufStream.write(allBytes[i]);
  90.             bufStream.close();
  91.         } catch (IOException e)// handle any errors
  92.             {
  93.                 System.out.println("Error - " + e.toString());
  94.             }//catch
  95.     }//main
  96. }//BufferedWriteStream
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
  103. BufferedReadStream.java:
  104.  
  105. import java.io.*;
  106.  
  107. public class BufferedReadStream
  108. {
  109.     // This program runs as an application
  110.     public static void main(String[] arguments)
  111.     {
  112.         try
  113.         {
  114.             //declare a stream
  115.             FileInputStream ifile = new FileInputStream("bufBytes.dat");
  116. BufferedInputStream bufStream = new BufferedInputStream(ifile);
  117. boolean eof = false;
  118.             int cntBytes = 0;
  119.             while (!eof)
  120.             {
  121.                int thisVal = bufStream.read();
  122.                System.out.print( thisVal + " ");
  123.                if (thisVal == -1)
  124.                   eof = true;
  125.                else
  126.                   cntBytes++;
  127.             } //while
  128.             bufStream.close();
  129.             System.out.print("\nBytes read: " + cntBytes);
  130.  
  131.        } catch (IOException e)// handle any errors
  132.             {
  133.                 System.out.println("Error - " + e.toString());
  134.             }//catch
  135.     }//main
  136. }//BufferedReadStream
  137.  
  138.  
  139.  
  140.  
  141.  
  142.  
  143.  
  144.  
  145.  
  146. BufferedWriteDataStream.java:
  147.  
  148. import java.io.*;
  149.  
  150. public class BufferedWriteDataStream
  151. {
  152.     // This program runs as an application
  153.     public static void main(String[] arguments)
  154.     {
  155.         //Create an array of data to print
  156.         double[] allDoubles = {1.1,3.1,5.1,7.1,9.1,11.1,13.1,15.1,17.1,19.1,21.1,23.1,25.1,27.1,29.1};
  157. try
  158.         {
  159.             //declare a stream and attach it to a file
  160.             FileOutputStream ofile = new FileOutputStream("bufDouble.dat");
  161.  
  162.             //declare a buffer and attach it to a stream
  163.             BufferedOutputStream bufStream = new BufferedOutputStream(ofile);
  164.  
  165.             //declare a data stream and assign it to a buffer
  166.             DataOutputStream datStream = new DataOutputStream(bufStream);
  167.  
  168.             for (int i=0; i < allDoubles.length; i++)
  169.                 //write to the datastream
  170.                 datStream.writeDouble(allDoubles[i]);
  171.             datStream.close();
  172.         } catch (IOException e)// handle any errors
  173.             {
  174.                 System.out.println("Error - " + e.toString());
  175.             }//catch
  176.     }//main
  177. }//BufferedWriteDataStream
  178.  
  179.  
  180.  
  181.  
  182.  
  183.  
  184.  
  185.  
  186. BufferedReadDataStream.java:
  187.  
  188. import java.io.*;
  189.  
  190. public class BufferedReadDataStream
  191. {
  192.     // This program runs as an application
  193.     public static void main(String[] arguments)
  194.     {
  195.         try
  196.         {
  197.             //declare a stream
  198.             FileInputStream ifile = new FileInputStream("bufDouble.dat");
  199. BufferedInputStream bufStream = new BufferedInputStream(ifile);
  200. DataInputStream datStream = new DataInputStream(bufStream);
  201. int cntDoubles = 0;
  202.             try
  203.             {
  204.                 while (true)
  205.                 {
  206.                     double thisVal = datStream.readDouble();
  207.                     System.out.print( thisVal + " ");
  208.                     cntDoubles++;
  209.                 } //while
  210.             } catch (EOFException eof)
  211.                 {
  212.                     datStream.close();
  213.                     System.out.print("\nDoubles read: " + [ccc]
  214. cntDoubles);
  215. } //catch
  216.  
  217.        } catch (IOException e)// handle any errors
  218.             {
  219.                 System.out.println("Error - " + e.toString());
  220.             }//catch
  221.     }//main
  222. }//BufferedReadDataStream
  223.  
  224.  
  225.  
  226.  
  227.  
  228.  
  229.  
  230. BufferedWriteCharStream.java:
  231.  
  232. import java.io.*;
  233.  
  234. public class BufferedWriteCharStream
  235. {
  236.     // This program runs as an application
  237.     public static void main(String[] arguments)
  238.     {
  239.         //Create an array of data to print
  240.         char[] allChars = {'H','e','l','l','o',' ','W','o','r','l','d','\n'};
  241. try
  242.         {
  243.             //declare a stream and attach it to a file
  244.             FileWriter ofile = new FileWriter("bufChar.dat");
  245.  
  246.             //declare a BufferedWriter - attach it to a stream
  247.             BufferedWriter bufStream = new BufferedWriter(ofile);
  248.  
  249.             for (int i=0; i < allChars.length; i++)
  250.                 //write to the char stream
  251.                 bufStream.write(allChars[i]);
  252.             bufStream.close();
  253.         } catch (IOException e)// handle any errors
  254.             {
  255.                 System.out.println("Error - " + e.toString());
  256.             }//catch
  257.     }//main
  258. }//BufferedWriteCharStream
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265. BufferedReadCharStream.java:
  266.  
  267. import java.io.*;
  268.  
  269. public class BufferedReadCharStream
  270. {
  271.     // This program runs as an application
  272.     public static void main(String[] arguments)
  273.     {
  274.         try
  275.         {
  276.             //declare a stream
  277.             FileReader ifile = new FileReader("bufChar.dat");
  278.             BufferedReader bufStream = new BufferedReader(ifile);
  279. boolean eof = false;
  280.             while (!eof)
  281.             {
  282.                 String line = bufStream.readLine();
  283.                 if (line == null)
  284.                     eof = true;
  285.                 else
  286.                     System.out.println(line);
  287.             }//while
  288.             bufStream.close();
  289.  
  290.        } catch (IOException e)// handle any errors
  291.             {
  292.                 System.out.println("Error - " + e.toString());
  293.             }//catch
  294.     }//main
  295. }//BufferedReadStream
  296.  
  297.  
  298.  
  299.  
  300.  
  301.  
  302.  
  303.  
  304. GetInetFile.java:
  305.  
  306. import java.awt.*;
  307. import java.awt.event.*;
  308. import java.net.*;
  309. import java.io.*;
  310.  
  311. public class GetInetFile extends Frame implements Runnable
  312. {
  313.     Thread thread1;
  314.     URL doc;
  315.     TextArea body = new TextArea("Getting text...");
  316.  
  317.     public GetInetFile()
  318.     {
  319.        super("Get URL");
  320.        add(body);
  321.        try
  322.        {
  323.             doc = new URL("http://www.lads.com/ads/launch.html");
  324. }//try
  325.        catch (MalformedURLException e)
  326.        {
  327.             System.out.println("Bad URL:  " + doc);
  328.        }//catch
  329.  
  330.     }//GetInetFile
  331.  
  332.  
  333.     public static void main(String[] arguments)
  334.     {
  335.        GetInetFile frame1 = new GetInetFile();
  336.  
  337.        WindowListener l = new WindowAdapter()
  338.        {
  339.             public void windowClosing(WindowEvent e) 
  340.             {
  341.                 System.exit(0);
  342.             }//windowClosing
  343.        };//WindowListener
  344.  
  345.        frame1.addWindowListener(l);
  346.        frame1.pack();
  347.        frame1.setVisible(true);
  348.        if (frame1.thread1 == null)
  349.        {
  350.           frame1.thread1 = new Thread(frame1);
  351.           frame1.thread1.start();
  352.        }//null
  353.     }//main
  354.  
  355.     public void run()
  356.     {
  357.        URLConnection URLConn = null;
  358.        InputStreamReader inStream;
  359.        BufferedReader info;
  360.        String line1;
  361.        StringBuffer strBuffer = new StringBuffer();
  362.        try
  363.        {
  364.           URLConn = this.doc.openConnection();
  365.           URLConn.connect();
  366.           body.setText("Connection opened ... ");
  367.           inStream = new InputStreamReader(URLConn.getInputStream());
  368. info = new BufferedReader(inStream);
  369.           body.setText("Reading data ...");
  370.           while ((line1 = info.readLine()) != null)
  371.           {
  372.                 strBuffer.append(line1 + "\n");
  373.           }//while
  374.           body.setText(strBuffer.toString());
  375.        }//try
  376.        catch (IOException e)
  377.        {
  378.           System.out.println("IO Error:" + e.getMessage());
  379.        }//catch
  380.     }//run
  381. }// class Getfile
  382.  
  383.  
  384.  
  385.  
  386.  
  387. Advertiser.java:
  388.  
  389. import java.util.*;
  390. import java.awt.*;
  391. import java.awt.event.*;
  392. import java.applet.Applet;
  393. import java.net.*;
  394.  
  395. /*
  396.  * A class which performs the banner animation
  397.  */
  398. class Banner extends Panel implements Runnable{
  399.  
  400. /*
  401.  * an instance of the applet for
  402.  * invoking methods from Advertiser class
  403. */
  404. Advertiser advertiser;
  405.  
  406. /*
  407.  * instance of thread used for animation
  408.  */
  409. Thread thread;
  410.  
  411. /*
  412.  * the next banner image to be displayed
  413.  */
  414. Image theImage;
  415.  
  416. /*
  417.  * width and height of the new banner image
  418.  */
  419. int img_width, img_height;
  420.  
  421. /*
  422.  * offscreen image for double-buffering
  423.  */
  424. Image offscreen;
  425.  
  426. /*
  427.  * offg1 is the graphics object associated with
  428.  * offscreen image. offg2 is the clipped version
  429.  * of offg1
  430.  */
  431. Graphics offg1, offg2;
  432.  
  433. /*
  434.  * xstart, ystart - x and y coordinate of clipping rectangle
  435.  * width, height - width and height of clipping rectangle
  436.  * effect_type - the effect type applied the next image
  437.  */
  438. int xstart, ystart, width, height, effect_type;
  439.  
  440. /**
  441.  * constructor just saves instance of the applet
  442.  * @param advertiser - instance of Advertiser applet
  443.  */
  444. Banner (Advertiser advertiser) {
  445.  
  446.     this.advertiser = advertiser;
  447.  
  448. }
  449.  
  450. /*
  451.  * thread that calls repaint() every 25 ms
  452.  * to effect animation
  453.  */
  454. public void run() {
  455.  
  456.     Dimension d = getSize();
  457.     offscreen = createImage (d.width, d.height);
  458.     offg1 = offscreen.getGraphics ();
  459.     offg1.setFont (getFont ());
  460.     offg1.setColor (Color.gray);
  461.     offg1.fillRect (0, 0, d.width, d.height);
  462.     while (true) {
  463.         repaint ();
  464.         try {
  465.             Thread.sleep (25);
  466.         } catch (InterruptedException e) {
  467.             break;
  468.         }
  469.     }
  470. }
  471.  
  472. /**
  473.  * override update() method to avoid erase flicker
  474.  * this is where the drawing is done
  475.  * @param g - destination graphics object
  476.  */
  477. public synchronized void update(Graphics g) {
  478.  
  479.     int i, x, y, w, h;
  480.     switch (effect_type) {
  481.         case 0:
  482.         offg1.drawImage (theImage, 0, 0, null);
  483.         break;
  484.  
  485.         case 1:        // barn-door open
  486.         if (xstart > 0) {
  487.             xstart -= 5;
  488.             width += 10;
  489.             offg2 = offg1.create (xstart, 0, width, height);
  490.             offg2.drawImage (theImage, -xstart, 0, null);
  491.         } else offg1.drawImage (theImage, 0, 0, null);
  492.         break;
  493.  
  494.         case 2:        // venetian blind
  495.         if (height < 10) {
  496.             height += 1;
  497.             for (y=0; y<img_height; y+=10) {
  498.                 offg2 = offg1.create (0, y, width, height);
  499.                 offg2.drawImage (theImage, 0, -y, null);
  500.             }
  501.         } else offg1.drawImage (theImage, 0, 0, null);
  502.         break;
  503.  
  504.         case 3:        // checker board
  505.         if (width <= 20) {
  506.             if (width <= 10) {
  507.                 i = 0;
  508.                 for (y=0; y<img_height; y+=10) {
  509.                     for (x=(i&1)*10; x<img_width; x+=20) {
  510.                         offg2 = offg1.create (x, y, width, 10);
  511.                         offg2.drawImage (theImage, -x, -y, null);
  512. }
  513.                     i += 1; 
  514.                 }
  515.             } else {
  516.                 i = 1;
  517.                 for (y=0; y<img_height; y+=10) {
  518.                     for (x=(i&1)*10; x<img_width; x+=20) {
  519.                         offg2 = offg1.create (x, y, width-10, 10);
  520. offg2.drawImage (theImage, -x, -y, null);
  521. }
  522.                     i += 1;
  523.                 }
  524.             }
  525.             width += 5;
  526.         } else offg1.drawImage (theImage, 0, 0, null);
  527.         break;
  528.     }
  529.     g.drawImage (offscreen, 0, 0, null); 
  530. }
  531.  
  532. /**
  533.  * Initialize variables for clipping rectangle
  534.  * depending on effect type
  535.  * @param which - the effect type for next image
  536.  * @param img - the next image
  537.  */
  538. public void effect (int which, Image img) {
  539.  
  540.     img_width = img.getWidth (null);
  541.     img_height = img.getHeight (null);
  542.     theImage = img;
  543.     switch (which) {
  544.         case 0:
  545.         break;
  546.  
  547.         case 1:        // barn door
  548.         xstart = img_width >> 1;
  549.         width = 0;
  550.         height = img_height;
  551.         break;
  552.  
  553.         case 2:
  554.         width = img_width;
  555.         height = 0;
  556.         break;
  557.  
  558.         case 3:
  559.         width = 0;
  560.         break;
  561.     }
  562.     effect_type = which; 
  563. }
  564.  
  565. /*
  566.  * Start the repaint thread
  567.  */
  568. public void start() {
  569.  
  570.     thread = new Thread(this);
  571.     thread.start();
  572. }
  573.  
  574. /*
  575.  * Stop the repaint thread
  576.  */
  577. public void stop() {
  578.  
  579.     if (thread != null)
  580.        thread = null;
  581. }
  582.  
  583.  
  584. }
  585.  
  586. /*
  587.  * the Advertiser class proper
  588. */
  589. public class Advertiser extends Applet implements Runnable, MouseListener  {
  590.  
  591. /*
  592.  * instance of Banner
  593.  */
  594. Banner panel;
  595.  
  596. /*
  597.  * instance of thread for cycling effects
  598.  * for each new image
  599.  */
  600. Thread thread;
  601.  
  602. /*
  603.  * the total number of images
  604.  */
  605. int NBanners; 
  606.  
  607. /*
  608.  * the array of images
  609.  */
  610. Image img[] = new Image[10];
  611.  
  612. /*
  613.  * the delay (dwell) time in milliseconds for each image
  614.  */
  615. int delay[] = new int[10];
  616.  
  617. /*
  618.  * the effect type for each image
  619.  */
  620. int effect[] = new int[10];
  621.  
  622. /*
  623.  * the URL to go to for each image
  624.  */
  625. URL url[] = new URL[10];
  626.  
  627. /*
  628.  * the index variable pointing to the
  629.  * current image, delay time, and associated URL
  630.  */
  631. int current = 0;
  632.  
  633. /*
  634.  * called when applet is loaded
  635.  * add the banner panel, load images, and parse applet
  636.  * parameters
  637.  */
  638. public void init() {
  639.  
  640.     int i;
  641.     setLayout(new BorderLayout());
  642.  
  643.     panel = new Banner (this);
  644.     panel.addMouseListener(this);
  645.  
  646.     add("Center", panel);
  647.     NBanners = 0;
  648.     MediaTracker tracker = new MediaTracker (this); 
  649.  
  650.     for (i=1; i<=10; i+=1) {
  651.         String param, token;
  652.         int j, next;
  653.  
  654.         param = getParameter ("T"+i);
  655.         if (param == null) break;
  656.  
  657.         StringTokenizer st = new StringTokenizer (param, " ,"); 
  658.  
  659.         token = st.nextToken ();
  660.         img[NBanners] = getImage (getDocumentBase(), token);
  661.         tracker.addImage (img[NBanners], i);
  662.         showStatus ("Getting image: "+token);
  663.         try {
  664.             tracker.waitForID (i);
  665.         } catch (InterruptedException e) { }
  666.  
  667.         token = st.nextToken ();
  668.         delay[NBanners] = Integer.parseInt (token);
  669.  
  670.         token = st.nextToken ();
  671.         effect[NBanners] = Integer.parseInt (token);
  672.  
  673.         token = st.nextToken ();
  674.         try {
  675.             url[NBanners] = new URL (token);
  676.         } catch (MalformedURLException e) {
  677.             url[NBanners] = null;
  678.         }
  679.  
  680.         NBanners += 1;
  681.     }
  682. }
  683.  
  684. /*
  685.  * thread that starts the next image transition
  686.  */
  687. public void run () {
  688.  
  689.     while (true) {
  690.         panel.effect (effect[current], img[current]);
  691.         try {
  692.             Thread.sleep (delay[current]);
  693.         } catch (InterruptedException e) { }
  694.         current += 1;
  695.         current %= NBanners;
  696.     }
  697. }
  698.  
  699. /*
  700.  * called when applet is started
  701.  * start both threads
  702.  */
  703. public void start() {
  704.  
  705.     panel.start();
  706.     thread = new Thread(this); 
  707.     thread.start();
  708. }
  709.  
  710. /*
  711.  * called when applet is stopped
  712.  * stops all threads
  713.  */
  714. public void stop() {
  715.  
  716.     panel.stop();
  717.     if (thread != null)
  718.        thread = null;
  719. }
  720. /**
  721.  * Called when user clicks in the applet
  722.  * Force the browser to show the associated URL
  723.  * MouseListener required methods*/
  724. /////////////////////////////////////////////////////////////
  725. /////////////////////////////////////////////////////////////
  726. public void mouseClicked(MouseEvent e){}
  727. public void mouseEntered(MouseEvent e){}
  728. public void mouseExited(MouseEvent e){}
  729.  
  730. public void mouseReleased(MouseEvent e){}
  731.  
  732.  
  733. public void mousePressed(MouseEvent e)
  734. {
  735.  
  736.     if (url[current] != null)
  737.     {
  738.         System.out.println("current " + url[current]);
  739.         getAppletContext().showDocument (url[current]);
  740.     }
  741. }
  742.  
  743. /////////////////////////////////////////////////////////////
  744. /////////////////////////////////////////////////////////////
  745.  
  746. }
  747.  
  748.  
  749.  
  750.  
  751.  
  752.  
  753.  
  754. Lookup.java:
  755.  
  756. import java.awt.*;
  757. import java.awt.event.*;
  758. import java.net.*;
  759. import java.applet.*;
  760.  
  761. /*
  762.  * Lookup application class
  763.  */
  764. public class Lookup extends Applet implements ActionListener  {
  765.  
  766. /*
  767.  * text field for host name
  768.  */
  769. TextField nameField;
  770.  
  771. Button btnLookup;
  772.  
  773. /*
  774.  * text area for displaying Internet addresses
  775.  */
  776. TextArea addrArea;
  777.  
  778. /*
  779.  * instance of InetAddress needed for name-to-address
  780.  * translation
  781.  */
  782. InetAddress inetAddr;
  783.  
  784. /*
  785.  * insertion point in the Internet address
  786.  * text area
  787.  */
  788. int insertIndex;
  789.  
  790. /*
  791.  * constructor creates user interface
  792.  */
  793. public void init () {
  794.  
  795.     super.init();
  796.  
  797.     setLayout (new BorderLayout ());
  798.  
  799.     Panel editPanel = new Panel ();
  800.     editPanel.setLayout (new BorderLayout ());
  801.     editPanel.add ("North", new Label ("Host name"));
  802.     nameField = new TextField ("", 32);
  803.     btnLookup = new Button("Lookup");
  804.     editPanel.add ("Center", nameField);
  805.     editPanel.add ("South", btnLookup);
  806.  
  807.     add ("North", editPanel);
  808.  
  809.     Panel areaPanel = new Panel ();
  810.     areaPanel.setLayout (new BorderLayout ());
  811.     addrArea = new TextArea ("", 24, 32);
  812.     addrArea.setEditable (false);
  813.     areaPanel.add ("North", new Label ("Internet address"));
  814.     areaPanel.add ("Center", addrArea); 
  815.  
  816.     add ("Center", areaPanel);
  817.     btnLookup.addActionListener(this);
  818.  
  819.     insertIndex = 0;
  820.  
  821.     setSize (300, 200);
  822. }
  823.  
  824.     public void actionPerformed(ActionEvent ev)
  825.     {
  826.         String name = nameField.getText ();
  827.         try
  828.         {
  829.             inetAddr = InetAddress.getByName (name);
  830.             String str = inetAddr.toString () + "\n";
  831.             addrArea.insert (str, insertIndex);
  832.             insertIndex += str.length ();
  833.         } catch (UnknownHostException ex)
  834.              {
  835.                 String str = name + "/ No such host\n";
  836.                 addrArea.insert (str, insertIndex);
  837.                 insertIndex += str.length ();
  838.              }
  839.     }
  840.  
  841. } // end of Applet
  842.  
  843.  
  844.  
  845.  
  846.  
  847.  
  848.  
  849. Ping.java:
  850.  
  851. import java.awt.*;
  852. import java.awt.event.*;
  853. import java.io.*;
  854. import java.net.*;
  855.  
  856. /*
  857.  * application class
  858.  */
  859. public class Ping extends Frame implements Runnable, ActionListener {
  860.  
  861. /*
  862.  * instance of Socket used for determining
  863.  * whether remote host is alive
  864. */
  865. Socket socket;
  866.  
  867. /*
  868.  * hostname text entry field
  869.  */
  870. TextField addrField;
  871.  
  872. /*
  873.  * the stop button
  874.  */
  875. Button stopButton;
  876. Button startButton;
  877.  
  878. /*
  879.  * the text area for printing remote
  880.  * host status
  881.  */
  882. TextArea content;
  883.  
  884. /*
  885.  * thread used to decouple user activity
  886.  * from socket activity
  887.  */
  888. Thread thread;
  889.  
  890. /*
  891.  * text area insert position
  892.  */
  893. int insertPos;
  894.  
  895. /*
  896.  * constructor creates user interface
  897.  */
  898. public Ping () {
  899.  
  900.     int i; 
  901.  
  902.     setTitle ("Ping");
  903.     setLayout(new BorderLayout());
  904.  
  905.     addrField = new TextField ("", 20);
  906.     startButton = new Button ("Start");
  907.     stopButton = new Button ("Stop");
  908.     content = new TextArea ("", 24, 80);
  909.     content.setEditable (false);
  910.     insertPos = 0;
  911.  
  912.     Panel p = new Panel ();
  913.     p.setLayout (new FlowLayout ());
  914.     p.add (addrField);
  915.     p.add (startButton);
  916.     p.add (stopButton);
  917.  
  918.     startButton.addActionListener(this);
  919.     stopButton.addActionListener(this);
  920.     addWindowListener(new WindowCloser());
  921.  
  922.  
  923.     add ("North", p);
  924.     add ("Center", content);
  925.  
  926.     thread = new Thread (this);
  927.  
  928.     setSize (400, 300);
  929.     show ();
  930. }
  931.  
  932. /**
  933.  * handle action events
  934.  * Enter keypress starts socket open thread
  935.  * Stop button click stops socket thread
  936. * @param evt - event object
  937.  * @param obj - object receiving this event
  938.  */
  939. public void actionPerformed (ActionEvent ev)
  940. {
  941.     Object object1 = ev.getSource();
  942.     if (object1 == startButton)
  943.     {
  944.         if (thread != null)
  945.             thread = null;
  946.         thread = new Thread (this);
  947.         thread.start ();
  948.     }
  949.     if (object1 == stopButton)
  950.     {
  951.         if (thread!= null)
  952.            thread = null;
  953.     }
  954. }
  955.  
  956. /*
  957.  * socket open thread
  958.  * tries to open the telnet port (23)
  959.  */
  960. public void run () {
  961.  
  962.     String name;
  963.  
  964.     name = addrField.getText ();
  965.         try {
  966.                 try {
  967.                         socket = new Socket (name, 23); 
  968.                 } catch (UnknownHostException e) {
  969.                         insertString (name+" :unknown host\n");
  970.                         return;
  971.                 }
  972.         } catch (IOException e2) {
  973.                 insertString ("Unable to open socket\n");
  974.                 return;
  975.         }
  976.  
  977.     insertString (name + " is alive\n");
  978.     try {
  979.         socket.close ();
  980.         } catch (IOException e2) {
  981.                 insertString ("IOException closing socket\n");
  982.  
  983.                 return;
  984.         }
  985. }
  986.  
  987. /**
  988.  * helper method for adding text to the end
  989.  * of the text area
  990.  * @param s - text to add
  991.  */
  992. void insertString (String s) {
  993.  
  994.     content.insert (s, insertPos);
  995.     insertPos += s.length ();
  996. }
  997.  
  998. /**
  999.  * application entry point
  1000.  * @param args - command-line arguments
  1001.  */
  1002. public static void main (String args[]) {
  1003.  
  1004.     new Ping ();
  1005. }
  1006. }
  1007.  
  1008. class WindowCloser extends WindowAdapter
  1009. {
  1010.     public void windowClosing(WindowEvent e)
  1011.     {
  1012.         Window win = e.getWindow();
  1013.         win.setVisible(false);
  1014.         win.dispose();
  1015.         System.exit(0);
  1016.     }
  1017. }
  1018.  
  1019.  
  1020.  
  1021.  
  1022.  
  1023.  
  1024.  
  1025.  
  1026.  
  1027.