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

public class NetworkServer {

	public static final int PORT = 12345;
	
	public static void main(String[] args) {
		try (
				//Create a ServerSocket (TCP)
				ServerSocket server = new ServerSocket(PORT);
				)
		{
			while(true) {
				//waits for a client to connect
				Socket socket = server.accept();
				
				//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());
				
				//start the conversation (protocol)
				try (
						//set up the communication streams
						Scanner inFromClient = new Scanner(socket.getInputStream());
						PrintWriter outToClient = new PrintWriter(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();
				}
			}
			
		}
		catch(Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
	}

}
