/**
 * An application which demonstrates how to implement a mini network
 * server using sockets.
 *
 * This server waits for a connection from a client on port 999 and
 * echo back to the client every line it receives.
 *
 * @version	$Id: EchoServer.java,v 1.2 2003/01/15 08:13:05 nthiery Exp $
 * @author	Nicolas M. Thiéry <nthiery@users.sourceforge.net>
**/

import java.io.*;
import java.net.*;

public class EchoServer {
    public static void main(String args[]) {

	try { // Protection against failures of network operations

	    // Get the name of the host
	    InetAddress localAddress= InetAddress.getLocalHost();
	    String hostname = localAddress.getHostName();

	    // Try to open a server socket on port 9999
	    // Note that, on UNIX, we can't choose a port number less than
	    // 1023 if we are not a privileged user (root)
	    int port = 9999;
            ServerSocket serverSocket = new ServerSocket(port);
	    System.err.println("Waiting for connection on host "+hostname+" port "+port);

	    // Listen and accept a connection on ServerSocket
	    // This returns a new socket object connected to the client.
            Socket clientSocket = serverSocket.accept();
	    System.err.println("Client connected");

	    // Open input and output streams from the socket
	    BufferedReader inputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintStream     outputStream = new PrintStream(clientSocket.getOutputStream());

	    // As long as we receive data, echo that data back to the client.
	    String line;
            while ((line = inputStream.readLine())!=null) {
		System.err.println("Client: "+line);
		outputStream.println(line);
	    }
	    System.err.println("Client deconnected");
	}
	catch (IOException e) {
            System.out.println(e);
	}
    }
}
