Guest User

Untitled

a guest
Mar 30th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. import java.lang.*;
  2. import java.io.*;
  3. import java.net.*;
  4.  
  5. class Server {
  6. public static void main(String args[]) {
  7. String welcome = "Welcome! The server is connected.";
  8. String message, login;
  9.  
  10. try {
  11. //Detecting the localhost's ip address
  12. InetAddress localaddr = InetAddress.getLocalHost();
  13. System.out.println("SERVER");
  14. System.out.println ("Local hostnameIP: " + localaddr );
  15.  
  16. // Creating a server socket for connection
  17. ServerSocket srvr = new ServerSocket(1234);
  18. System.out.println("Waiting for connection on "+localaddr);
  19. // Accept incoming connection
  20. Socket skt = srvr.accept();
  21. System.out.print("Server has connected!\n");
  22. // get Input and Output streams
  23. PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
  24. out.flush();
  25. BufferedReader in = new BufferedReader(new
  26. InputStreamReader(skt.getInputStream()));
  27. System.out.print("Sending string: '" + welcome + "'\n");
  28. out.println(welcome);
  29.  
  30. //make new bufferedreader or close out & make another input for user + pass
  31.  
  32. //login
  33. System.out.println("Enter the username and password:");
  34.  
  35. out.print("Username: ");
  36. String username = in.readLine();
  37. System.out.println("Client's username: " + username);
  38.  
  39. out.print("Password: ");
  40. String password = in.readLine();
  41. System.out.println("Client's password: " + password);
  42.  
  43. if (username.equals("hello123")) {
  44. out.println("Correct username!");
  45. }
  46. if (password.equals("mypass")) {
  47. out.println("Correct password!");
  48. }
  49.  
  50.  
  51. do {
  52.  
  53. message=in.readLine();
  54. System.out.println("client>"+message);
  55. if (message.equals("password")){
  56. out.println("Access Granted");
  57. System.out.println ("Client's IP Address: " + localaddr.getHostAddress());
  58. }else if (message.equals("bye")){
  59. out.println("Server closing");
  60. System.out.println("server>Server closing");
  61. }
  62. }while(!message.equals("bye"));
  63. out.close();
  64. skt.close();
  65. srvr.close();
  66. }catch(BindException e){
  67. //e.printStackTrace();
  68. System.out.print("A server is already running on the same port.");
  69. }catch(SocketException e) {
  70. //e.printStackTrace();
  71. System.out.print("Client has disconnected rudely.");
  72. }catch(Exception e){
  73. //e.printStackTrace();
  74. System.out.print(":( Whoops! It didn't work!\n");
  75.  
  76. }
  77. }
  78.  
  79.  
  80.  
  81. }
Add Comment
Please, Sign In to add comment