Esempio n. 1
0
  /**
   * This method waits for input from the console. Once it is received, it sends it to the client's
   * message handler.
   */
  public void accept() {
    try {
      BufferedReader fromConsole = new BufferedReader(new InputStreamReader(System.in));
      String message;

      while (true) {
        message = fromConsole.readLine();
        if (client == null) {
          client = new ChatClient(this);
        }
        client.handleMessageFromClientUI(message);
      }
    } catch (Exception ex) {
      System.out.println("Unexpected error while reading from console!");
    }
  }
 public void handleMessageFromClientUI(Object message) {
   String parsed = "";
   if (!((Message) message).message.startsWith("#") && isConnected()) {
     super.handleMessageFromClientUI(message);
     return;
   }
   {
     parsed = ((Message) message).message.substring(1);
     if (parsed.equals("quit")) {
       try {
         closeConnection();
       } catch (IOException ex) {
         ex.printStackTrace();
         System.exit(1);
       }
       System.exit(0);
     } else if (parsed.equals("logoff")) {
       try {
         closeConnection();
       } catch (IOException ex) {
         ex.printStackTrace();
         System.exit(1);
       }
     } else if (parsed.equals("login")) {
       if (isConnected()) {
         System.out.println("Error: Already connected");
         return;
       }
       try {
         openConnection();
       } catch (IOException ex) {
         System.out.println("Error: " + ex.getMessage());
         ex.printStackTrace();
       }
     } else if (parsed.startsWith("sethost")) {
       if (isConnected()) {
         System.out.println("Error: Already connected");
         return;
       } else {
         String host = "";
         try {
           host = parsed.split(" ")[1];
         } catch (ArrayIndexOutOfBoundsException ex) {
           System.out.println("Error: Must specify host");
           return;
         }
         setHost(host);
       }
     } else if (parsed.startsWith("setport")) {
       if (isConnected()) {
         System.out.println("Error: Already connected");
         return;
       }
       int port = 0;
       try {
         port = Integer.parseInt(parsed.split(" ")[1]);
       } catch (ArrayIndexOutOfBoundsException ex) {
         System.out.println("Error: Must specify port");
         return;
       }
       setPort(port);
     } else if (parsed.equals("getport")) {
       System.out.println("Port: " + getPort());
     } else if (parsed.equals("gethost")) {
       System.out.println("Host: " + getHost());
     }
   }
 }