/* File: EchoServer.java * * Adapted from an example by * Gary Cornell and Cay S. Horstmann, Core Java (Book/CD-ROM) * */ import java.io.*; import java.net.*; class EchoServer { public static void main(String[] args ) { try { // open a serversocket on port 4882 ServerSocket s = new ServerSocket( 4882 ); // the accept method waits for a message contacting the port // from a client Socket incoming = s.accept(); BufferedReader br = new BufferedReader( new InputStreamReader( incoming.getInputStream() ) ); PrintWriter out = new PrintWriter( incoming.getOutputStream(), true ); out.println( "Hello! Enter BYE to exit." ); // Echo lines back to the client until the client sends "BYE" boolean done = false; while ( !done ) { String str = br.readLine(); if ( str == null ) done = true; else { out.println( "Echo: " + str ); if ( str.trim().equals("BYE") ) done = true; } } // close the socket incoming.close(); } catch ( Exception e ) { System.out.println( e ); } } }