1 /* File: EchoServer.java 2 * 3 * Adapted from an example by 4 * Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM) 5 * 6 */ 7 8 import java.io.*; 9 import java.net.*; 10 11 class EchoServer 12 { 13 public static void main(String[] args ) 14 { try 15 { // open a serversocket on port 4882 16 ServerSocket s = new ServerSocket( 4882 ); 17 18 // the accept method waits for a message contacting the port 19 // from a client 20 Socket incoming = s.accept(); 21 22 BufferedReader br = 23 new BufferedReader( 24 new InputStreamReader( incoming.getInputStream() ) ); 25 PrintWriter out = 26 new PrintWriter( incoming.getOutputStream(), true ); 27 28 out.println( "Hello! Enter BYE to exit." ); 29 30 // Echo lines back to the client until the client sends "BYE" 31 boolean done = false; 32 while ( !done ) 33 { String str = br.readLine(); 34 if ( str == null ) done = true; 35 else 36 { out.println( "Echo: " + str ); 37 38 if ( str.trim().equals("BYE") ) 39 done = true; 40 } 41 } 42 // close the socket 43 incoming.close(); 44 } 45 catch ( Exception e ) 46 { System.out.println( e ); 47 } 48 } 49 } 50 51