import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class SocketExampleServer {
	public static final int SERVER_PORT = 5684;
	
	public static void main(String[] args) {
		try {
			ServerSocket socket = new ServerSocket(SERVER_PORT);
		
			System.out.println("Running on IP: " + socket.getInetAddress() + " and port: " + socket.getLocalPort());
			
			Socket nextSocket = null;
			while ((nextSocket = socket.accept()) != null) {
				BufferedInputStream in = new BufferedInputStream(nextSocket.getInputStream());
				byte[] bytes = new byte[100];
				int length = in.read(bytes);
				String name = "";
				while (length != -1) {
					name += new String(bytes, 0, length);
					length = in.read(bytes);
				}
				nextSocket.shutdownInput();
				
				System.out.println("Got name: " + name);
				
				PrintWriter out = new PrintWriter(nextSocket.getOutputStream());
				
				out.print("Hello " + name + "!  Your IP is " + nextSocket.getRemoteSocketAddress() + " You are using port " + nextSocket.getPort());
				out.flush();
				nextSocket.shutdownOutput();
				nextSocket.close();
			}
			socket.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

