Advertisement
Guest User

Untitled

a guest
May 19th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.31 KB | None | 0 0
  1. /**@file jserver.java
  2.  * @author Brittany Kondo 100379346
  3.  * @brief  Represents a multi-threaded server which can have several clients
  4.  *         connected to it, its main purpose is to manage all messages sent
  5.  *         among clients.
  6.  * */
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10. import java.io.PrintWriter;
  11. import java.net.ServerSocket;
  12. import java.net.Socket;
  13. import java.util.TreeMap;
  14. import java.util.Vector;
  15.  
  16.  
  17. public class jserver {
  18.     //Stores all messages for every client created on the server
  19.     public static TreeMap<String,Vector<String>> inbox = new TreeMap<String,Vector<String>>();
  20.    
  21.     /** Checks if a given user already exists on the server's inbox
  22.      * @param  map  The tree map (which represents the inbox) to search
  23.      * @param  user The user to search for
  24.      * @return      True, if the user already exists in the map
  25.      *              False, otherwise
  26.      * */
  27.     public static boolean doesUserExist(TreeMap<String,Vector<String>> map,String user){
  28.         for (String key:map.keySet()){
  29.             if (key.equalsIgnoreCase(user))
  30.                 return true;
  31.         }
  32.         return false;
  33.     }
  34.     //Handles an individual jclient and is used later to create a thread
  35.     //for each client
  36.     public static class jClientHandler implements Runnable {
  37.           private Socket client;   
  38.           /** Constructs a new jclienthandler object
  39.            * @param  client  A socket representing the client's connection to
  40.            *                 the server
  41.            * */
  42.           jClientHandler(Socket client) {
  43.            this.client = client;           
  44.           }
  45.          
  46.           /** Processes data received from the jclient class, invoked when the
  47.            * thread containing this handler is run in the main program.
  48.            * */
  49.           public void run(){
  50.             String line;
  51.             BufferedReader reader = null;
  52.             PrintWriter writer = null;
  53.             try{
  54.               //Initialize the reader and writer so that this socket can communicate with
  55.               //the jclient
  56.               reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
  57.               writer = new PrintWriter(client.getOutputStream(),true);
  58.             } catch (IOException e) {
  59.               e.printStackTrace();
  60.             }
  61.            
  62.               try{
  63.                 line = reader.readLine();
  64.                 //A new user is being added if there is a '1' appended to the beginning
  65.                 //of the line
  66.                 if ((line.charAt(0)=='1')&&(!doesUserExist(inbox,line.substring(1)))){
  67.                     //Add the user to the inbox map
  68.                     Vector <String> messages = new Vector<String>();
  69.                     inbox.put(line.substring(1), messages);                    
  70.                     System.out.println("Adding: "+line.substring(1));                  
  71.                    
  72.                 }
  73.                 //A message is being sent to a user if there is a '2' appended to the
  74.                 //beginning of the line
  75.                 else if (line.charAt(0)=='2'){
  76.                    
  77.                     //Search for the first index of the double colons in the line
  78.                     int indexOfColons = line.indexOf("::");
  79.                     //Extract the sender and recipient's name from the line
  80.                     String sender = line.substring(1,indexOfColons);
  81.                     String recipient = line.substring(indexOfColons+2);
  82.                     //Find the second occurrence of the double colons
  83.                     indexOfColons = recipient.indexOf("::");
  84.                     //Extract the message
  85.                     String message = recipient.substring(indexOfColons+2);
  86.                     recipient = recipient.substring(0,indexOfColons);                  
  87.                     message = sender + " : " + message;                                    
  88.                     //add the message to the user's inbox
  89.                     if (doesUserExist(inbox,recipient)){
  90.                         synchronized (inbox.get(recipient)){
  91.                         inbox.get(recipient).add(message);
  92.                         }                      
  93.                         System.out.println("Adding message to "+recipient+
  94.                                 " from " + sender+" \""+message+"\"");
  95.                     }
  96.                     else {
  97.                         System.out.println("User does not exist");
  98.                         writer.println("User does not exist");
  99.                     }                  
  100.                 }
  101.               //User wishes to retrieve their messages
  102.                 else if (line.charAt(0)=='3'){
  103.                     String userName = line.substring(1);
  104.                     if (!doesUserExist(inbox,userName)){                       
  105.                         writer.println("User does not exist");
  106.                         System.out.println("User does not exist");
  107.                     }
  108.                     else if (inbox.get(userName).size()>0){
  109.                         //Display the user's messages
  110.                         System.out.println("Writing " + userName + "'s messages: ");
  111.                         String messages = userName + "'s messages: \n";
  112.                         synchronized (inbox.get(userName)){
  113.                         for (String message:inbox.get(userName)){                          
  114.                             messages+=message + "\n";                          
  115.                         }          
  116.                         writer.println(messages);
  117.                         //clear all messages retrieved
  118.                         inbox.get(userName).clear();
  119.                         }
  120.                     }                          
  121.                     else {
  122.                         System.out.println("No messages to write");
  123.                         writer.println("No messages to display");          
  124.                     }      
  125.                    
  126.                 }
  127.                
  128.                writer.close();
  129.                reader.close();
  130.                } catch (IOException e) {
  131.                  e.printStackTrace();
  132.                }
  133.            
  134.           }
  135.         }
  136.  
  137.     public static void main(String[] args) {       
  138.         ServerSocket main = null;
  139.        
  140.         try {
  141.             main = new ServerSocket(1500);
  142.         } catch (IOException e1) {         
  143.             e1.printStackTrace();
  144.         }
  145.            
  146.             while(true) {
  147.                 jClientHandler cl;
  148.                 try {                      
  149.                 cl = new jClientHandler(main.accept());            
  150.                 Thread t = new Thread(cl);
  151.                 t.start();             
  152.                
  153.             } catch(IOException e) {
  154.                 System.out.println("Error: " + e.getMessage());
  155.             }              
  156.             }
  157.  
  158.     }
  159.  
  160.    }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement