home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / documentation / tutorial / networking / sockets / example / EchoTest.java < prev    next >
Encoding:
Java Source  |  1997-07-13  |  2.1 KB  |  56 lines

  1. /*
  2.  * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
  3.  *
  4.  * Permission to use, copy, modify, and distribute this software
  5.  * and its documentation for NON-COMMERCIAL purposes and without
  6.  * fee is hereby granted provided that this copyright notice
  7.  * appears in all copies. Please refer to the file "copyright.html"
  8.  * for further important copyright and licensing information.
  9.  *
  10.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  11.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  12.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  13.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  14.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  15.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  16.  */
  17. import java.io.*;
  18. import java.net.*;
  19.  
  20. public class EchoTest {
  21.     public static void main(String[] args) {
  22.         Socket echoSocket = null;
  23.         DataOutputStream os = null;
  24.         BufferedReader br = null;
  25.     BufferedReader stdIn = new BufferedReader(
  26.         new InputStreamReader(System.in));
  27.  
  28.         try {
  29.             echoSocket = new Socket("taranis", 7);
  30.             os = new DataOutputStream(echoSocket.getOutputStream());
  31.             br = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
  32.         } catch (UnknownHostException e) {
  33.             System.err.println("Don't know about host: taranis");
  34.         } catch (IOException e) {
  35.             System.err.println("Couldn't get I/O for the connection to: taranis");
  36.         }
  37.  
  38.         if (echoSocket != null && os != null && br != null) {
  39.             try {
  40.                 String userInput;
  41.  
  42.                 while ((userInput = stdIn.readLine()) != null) {
  43.                     os.writeBytes(userInput);
  44.                     os.writeByte('\n');
  45.                     System.out.println("echo: " + br.readLine());
  46.                 }
  47.                 os.close();
  48.                 br.close();
  49.                 echoSocket.close();
  50.             } catch (IOException e) {
  51.                 System.err.println("I/O failed on the connection to: taranis");
  52.             }
  53.         }
  54.     }
  55. }
  56.