Guest User

Untitled

a guest
Aug 31st, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.27 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5.  
  6. /**
  7.  *
  8.  * @author mxr808
  9.  */
  10. package groupworkGUI;
  11.  
  12.  
  13. import java.net.*;
  14. import java.io.*;
  15. import java.util.logging.Level;
  16. import java.util.logging.Logger;
  17.  
  18. public class HandlerThread extends Thread {
  19.     server myServer;
  20.     Socket sock;
  21.     boolean connected;
  22.     String username;
  23.     database accountdb;
  24.  
  25.     public HandlerThread(Socket s, server currentServer, database db)
  26.     {
  27.         try{
  28.         //Handler thread for each client. Specify socket on which client is operating, specify the server and the database.
  29.         myServer = currentServer;
  30.         sock = s;
  31.         connected = true;
  32.         accountdb = db;
  33.         boolean loggedIn= false;
  34.         System.out.println("Handler thread created for new connection");
  35.         try{
  36.         //Wait for client to select "1" (Login) or "2" (Create account)
  37.         BufferedReader readMessage = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  38.         String choice = readMessage.readLine();
  39.         //If 1, call login() method.
  40.         if(choice.equals("1"))
  41.         {
  42.             System.out.println(loggedIn);
  43.             while(loggedIn == false)
  44.             {
  45.              loggedIn = login();
  46.              System.out.println(loggedIn);
  47.  
  48.             }
  49.             start();
  50.             onlineUsers userUpdate = new onlineUsers();
  51.             userUpdate.start();
  52.         }
  53.         else
  54.         {
  55.         //Else create the account.
  56.         String username = readMessage.readLine();
  57.         String password = readMessage.readLine();
  58.         loggedIn = createAccount(username, password);
  59.         start();
  60.         onlineUsers userUpdate = new onlineUsers();
  61.         userUpdate.start();
  62.         }
  63.         }
  64.         catch(Exception e)
  65.         {
  66.             e.printStackTrace();
  67.             System.err.println("Exception in creation of handler thread");
  68.         }
  69.     }
  70.    
  71.     catch(Exception e)
  72.     {
  73.  
  74.     }
  75. }
  76.  
  77.  
  78.  
  79.     @Override
  80.     public void run()
  81.     {
  82.         try
  83.         {
  84.         while(connected == true)
  85.         {
  86.             //While running, wait for any received data over the socket.
  87.             System.out.println("Waiting for received messages");
  88.             System.out.println(sock);
  89.            
  90.             BufferedReader readMessage = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  91.             String message = readMessage.readLine();
  92.             System.out.println(message);
  93.  
  94.             //If null (Client has disconnected), remove the socket.
  95.             if(message == null)
  96.             {
  97.                 myServer.removeSocket(sock);
  98.                 System.out.println("Removed socket" + sock);
  99.                 accountdb.insertLog(username, "logged out", "N/A");
  100.                 connected = false;
  101.                
  102.             }
  103.  
  104.             //Otherwise, split the message by spaces.
  105.             else
  106.             {
  107.             System.out.println("Message received: " + message);
  108.  
  109.             //First index in that array is the target username.
  110.             String clientUsername = null;
  111.             String textMessage = null;
  112.             try{
  113.             clientUsername = message.substring(0, message.indexOf('@'));
  114.             textMessage = message.substring(clientUsername.length()+1, message.length());
  115.             }
  116.             catch(StringIndexOutOfBoundsException e)
  117.             {
  118.                
  119.             }
  120.  
  121.             //The message itself is the rest of the message.
  122.             //Send message to that username.
  123.             System.out.println("Sending message to: " + clientUsername);
  124.             accountdb.insertLog(username, "sent message", clientUsername);
  125.             myServer.sendChatMessage(clientUsername, myServer.getUsername(sock), textMessage);
  126.             while(myServer.wait == 1)
  127.             {
  128.                         Thread.sleep(1000);
  129.             }
  130.  
  131.             }
  132.         }
  133.         }
  134.         catch(Exception e)
  135.   {
  136.             System.out.println("Client Disconnected: " + sock);
  137.             System.out.println(e);
  138.             System.out.println(e.getMessage());
  139.             e.printStackTrace();
  140.             myServer.removeSocket(sock);
  141.         }
  142.     }
  143.  
  144.     //Client is attempting to login.
  145.     public boolean login()
  146.     {
  147.  
  148.  
  149.          String user = null;
  150.          String password = null;
  151.          try{
  152.              System.out.println("Ran login method");
  153.          //Wait for username and password to be received.
  154.          System.out.println("Ready to receive username/password");
  155.          BufferedReader readDetails = new BufferedReader(new InputStreamReader(sock.getInputStream()));
  156.          System.out.println("Received username/password");
  157.          username = readDetails.readLine();
  158.          password = readDetails.readLine();
  159.          for(int i = 0; i < myServer.usernames.length; i++)
  160.          {
  161.              if(myServer.usernames[i].equals(username))
  162.              {
  163.                           try{
  164.                               PrintWriter sendResult = new PrintWriter(sock.getOutputStream(), true);
  165.                               sendResult.println("false");
  166.                                 }
  167.                               catch(Exception e)
  168.                               {
  169.  
  170.                               }
  171.                  return false;
  172.              }
  173.          }
  174.  
  175.          }
  176.          catch(Exception e)
  177.          {
  178.              System.out.println("Error receiving login");
  179.         }
  180.          //Split message by space.
  181.          System.out.println("Received: " + username + " " + password);
  182.          //Username is at 0 index, password at index 1.
  183.          //Call the database checkLogin on these details. If returns true
  184.          //tell the client they succeeded.
  185.          //CHANGE TO accountdb.checkLogin(username, password)
  186.          //username.equals("test")||username.equals("test1");
  187.          if(accountdb.checkLogin(username, password))
  188.          {
  189.                      myServer.addUser(username, sock);
  190.                      System.out.println("User " + username + " logged in successfully");
  191.                      accountdb.insertLog(username, "Logged in", "N/A");
  192.                      try{
  193.                      PrintWriter sendResult = new PrintWriter(sock.getOutputStream(), true);
  194.                      System.out.println("Sending result of login");
  195.                      sendResult.println("true");
  196.                      }
  197.                      catch(Exception e)
  198.                      {
  199.                          System.out.println("Error");
  200.                      }
  201.                      return true;
  202.         }
  203.                  //If returns false:
  204.                  else
  205.                  {
  206.                      System.out.println("Password incorrect");
  207.                               System.out.println("Username not found");
  208.                               try{
  209.                               PrintWriter sendResult = new PrintWriter(sock.getOutputStream(), true);
  210.                               sendResult.println("false");
  211.                                 }
  212.                               catch(Exception e)
  213.                               {
  214.  
  215.                               }
  216.                                 return false;
  217.                                 }
  218.              
  219.          
  220.  
  221.  
  222.  
  223.        
  224.     }
  225.  
  226.     public boolean createAccount(String newUsername, String password)
  227.     {
  228.  
  229.         System.out.println("Creating account");
  230.         boolean result = accountdb.createAccount(newUsername, password);
  231.         //boolean result = true;
  232.  
  233.         System.out.println("createAccount: " + result);
  234.         if(result)
  235.         {
  236.             PrintWriter sendResult = null;
  237.             try {
  238.                 sendResult = new PrintWriter(sock.getOutputStream(), true);
  239.                 System.out.println("Sending result of login");
  240.                 sendResult.println("true");
  241.                 System.out.println("Returned true after telling database to create account");
  242.                 myServer.addUser(newUsername, sock);
  243.                 username = newUsername;
  244.                 accountdb.insertLog(username, "Created Account", "N/A");
  245.                 return true;
  246.             } catch (IOException ex) {
  247.                 Logger.getLogger(HandlerThread.class.getName()).log(Level.SEVERE, null, ex);
  248.                 return false;
  249.             }
  250.         }
  251.         else
  252.         {
  253.             return false;
  254.         }
  255.        
  256.     }
  257.  
  258.     public String getUsername()
  259.     {
  260.         return username;
  261.     }
  262.  
  263.  
  264.  class onlineUsers extends Thread
  265. {
  266.     @Override
  267.     public void run()
  268.     {
  269.         while(true)
  270.         {
  271.             try{
  272.             Thread.sleep(5000);
  273.             StringBuffer onlineUsers = new StringBuffer("");
  274.             onlineUsers.append("|WhoIs|^");
  275.             for(int i = 0; i < myServer.usernames.length; i++)
  276.             {
  277.                 if(myServer.usernames[i] != null)
  278.                 {
  279.                 onlineUsers.append(" ");
  280.                 onlineUsers.append(myServer.usernames[i]);
  281.                 }
  282.  
  283.  
  284.             }
  285.                 PrintWriter userListSend = new PrintWriter(sock.getOutputStream(), true);
  286.                 userListSend.println(onlineUsers.toString());
  287.             }
  288.             catch(Exception e)
  289.             {
  290.  
  291.             }
  292.         }
  293.     }
  294. }
  295. }
Add Comment
Please, Sign In to add comment