package echo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * Version 1: an echo server that handles one client at a time. Each line the
 * client sends comes back as "echo: <line>"; "bye" ends the conversation.
 */
public class EchoServer {

	public static final int PORT = 6000;

	public static void main ( String[] args ) throws IOException {
		ServerSocket server = new ServerSocket(PORT);
		System.out.println("echo server listening on port " + PORT);

		for ( ; true ; ) {
			Socket socket = server.accept(); // blocks until a client connects
			System.out.println("connected: " + socket.getRemoteSocketAddress());
			handle(socket);
			System.out.println("disconnected: " + socket.getRemoteSocketAddress());
		}
	}

	/**
	 * Talks to one client until it says "bye" or disconnects.
	 */
	private static void handle ( Socket socket ) {
		try {
			BufferedReader in =
			    new BufferedReader(new InputStreamReader(socket.getInputStream(),
			                                             StandardCharsets.UTF_8));
			PrintWriter out =
			    new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),
			                                           StandardCharsets.UTF_8));

			for ( ; true ; ) {
				String line = in.readLine(); // blocks until a line arrives
				if ( line == null ) {
					break; // the client closed the connection
				}
				if ( line.equals("bye") ) {
					out.println("bye");
					out.flush();
					break;
				}
				out.println("echo: " + line);
				out.flush(); // send it now
			}
		} catch ( IOException e ) {
			System.out.println("problem talking to the client: " + e.getMessage());
		} finally {
			try {
				socket.close();
			} catch ( IOException e ) {}
		}
	}

}
