import java.lang.*; import java.io.*; import java.net.*; class Server { public static void main(String args[]) { String welcome = "Welcome! The server is now connected."; String login = "Enter username and password: "; String message; try { //Detecting the localhost's ip address InetAddress localaddr = InetAddress.getLocalHost(); System.out.println("SERVER\n"); System.out.println ("Local hostnameIP: " + localaddr ); // Creating a server socket for connection ServerSocket srvr = new ServerSocket(1234); System.out.println("Waiting for connection on "+localaddr); // Accept incoming connection Socket skt = srvr.accept(); System.out.print("Server has connected!\n"); // get Input and Output streams PrintWriter out = new PrintWriter(skt.getOutputStream(), true); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream())); BufferedReader log = new BufferedReader(new InputStreamReader(skt.getInputStream())); //read input for login System.out.print("Sending string: '" + welcome + "'\n"); out.println(welcome); out.println(login); //out.println(enterUser); //login //out.print("Username: "); String username = in.readLine(); System.out.println("Client's username: " + username); //out.print("Password: "); String password = in.readLine(); System.out.println("Client's password: " + password); if (username.equals("hello123") && password.equals("mypass")) { out.println("Correct login!"); System.out.println ("Client's IP Address: " + localaddr.getHostAddress()); } if (!username.equals("hello123")||!password.equals("mypass")) { out.println("Wrong login - server closing"); out.close(); skt.close(); srvr.close(); } do { message=in.readLine(); System.out.println("client> "+message); if (message.equals("password")){ out.println("Access Granted"); }else if (message.equals("bye")){ out.println("Server closing"); System.out.println("server> Server closing"); } }while(!message.equals("bye")); out.close(); skt.close(); srvr.close(); }catch(BindException e){ //e.printStackTrace(); System.out.print("A server is already running on the same port."); }catch(SocketException e) { //e.printStackTrace(); System.out.print("Client has disconnected rudely."); }catch(Exception e){ //e.printStackTrace(); System.out.print(":( Whoops! It didn't work!\n"); } } }