
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MTNetworkServer implements Runnable {

	public static final int PORT = 12345;
	
	protected Socket m_socket;
	
	//each object run by a thread
	public MTNetworkServer(Socket socket) {
		m_socket = socket;
		
		//get some info from the socket
		System.out.println("Connection established.");
		
		System.out.printf("From %s, %d\n",
				socket.getInetAddress().getHostName(),
				socket.getPort());
		
		System.out.printf("To %s, %d\n",
				socket.getLocalAddress().getHostName(),
				socket.getLocalPort());
	}
	
	public void run() {
		//start the conversation (protocol)
		try (
				//set up the communication streams
				Scanner inFromClient = new Scanner(m_socket.getInputStream());
				PrintWriter outToClient = new PrintWriter(m_socket.getOutputStream(), true);
				)
		{
			outToClient.println("Weclome!");
			//outToClient.flush();
			
			String line = inFromClient.nextLine();
			
			//end when client says quit
			while(!line.equalsIgnoreCase("QUIT")) {
				outToClient.printf("You sent: %s\n", line);
				//outToClient.flush();
				
				System.out.printf("Client sent: %s\n", line);
				
				line = inFromClient.nextLine();
				
			}
			outToClient.println("BYE");
		}
		catch(Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	
	
	public static void main(String[] args) {
		ExecutorService threadExec = Executors.newCachedThreadPool();
		
		try (
				//Create a ServerSocket (TCP)
				ServerSocket server = new ServerSocket(PORT);
				)
		{
			while(true) {
				//waits for a client to connect
				Socket socket = server.accept();
				
				MTNetworkServer connection = new MTNetworkServer(socket);
				
				//assign it to a thread and start running
				threadExec.execute(connection);
			}
			
		}
		catch(Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}

}
