Mega Code Archive

 
Categories / Java / Network Protocol
 

This program implements a simple server that listens to port 8189 and echoes back all client input

/*    This program is a part of the companion code for Core Java 8th ed.    (http://horstmann.com/corejava)    This program is free software: you can redistribute it and/or modify    it under the terms of the GNU General Public License as published by    the Free Software Foundation, either version 3 of the License, or    (at your option) any later version.    This program is distributed in the hope that it will be useful,    but WITHOUT ANY WARRANTY; without even the implied warranty of    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the    GNU General Public License for more details.    You should have received a copy of the GNU General Public License    along with this program.  If not, see <http://www.gnu.org/licenses/>. */ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; /**  * This program implements a simple server that listens to port 8189 and echoes back all client  * input.  * @version 1.20 2004-08-03  * @author Cay Horstmann  */ public class EchoServer {    public static void main(String[] args)    {       try       {          // establish server socket          ServerSocket s = new ServerSocket(8189);          // wait for client connection          Socket incoming = s.accept();          try          {             InputStream inStream = incoming.getInputStream();             OutputStream outStream = incoming.getOutputStream();             Scanner in = new Scanner(inStream);             PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);             out.println("Hello! Enter BYE to exit.");             // echo client input             boolean done = false;             while (!done && in.hasNextLine())             {                String line = in.nextLine();                out.println("Echo: " + line);                if (line.trim().equals("BYE")) done = true;             }          }          finally          {             incoming.close();          }       }       catch (IOException e)       {          e.printStackTrace();       }    } }