2013-05-22 77 views
0

好日子所有我新的Java和我想知道,如果有人可以幫我解決這個問題 我有一臺服務器,並從客戶端接收信息,但我的if語句來檢查值被通過不起作用。插座發送和檢索

這裏是我的服務器代碼。

Session(Socket s){ 
     soc = s; 
     try{ 
      br = new BufferedReader(new InputStreamReader(soc.getInputStream())); 

      pw = new PrintWriter(new BufferedOutputStream(soc.getOutputStream()),true); 
      pw.println("Welcome");   
     }catch(IOException ioe){ 
      System.out.println(ioe); 
     } 


     if(runner == null){ 
      runner = new Thread(this); 
      runner.start(); 
     } 
    } 

    public void run(){ 
     while(runner == Thread.currentThread()){ 
      try{ 
       String input = br.readLine().toString(); 
        if(input != null){ 
         String output = Protocol.ProcessInput(input); 
         pw.println(output); 
         System.out.println(input); 


         if(output.equals("Good Bye")){ 
          runner = null; 
          pw.close(); 
          br.close(); 
          soc.close(); 
         } 
       **This if statement doesn't work ↓** 
         if(Protocol.ProcessInput(input).equalsIgnoreCase("tiaan")){ 
          // System.exit(0); 
          System.out.println("Got tiaan!!!"); 
         } 
        } 

      }catch(IOException ie){ 
       System.out.println(ie); 
      } 
      try{ 
       Thread.sleep(10); 
      }catch(InterruptedException ie){ 
       System.out.println(ie); 
      } 
     } 
    } 


} 

class Protocol{ 
    static String ProcessInput(String input){ 
     if(input.equalsIgnoreCase("Hello")){ 
      return "Well hello to you to"; 
     }else{ 
      return "Good bye"; 
     } 
    } 
} 

回答

2

確定。讓我們來看看,如果聲明:

if(Protocol.ProcessInput(input).equalsIgnoreCase("tiaan")){ 
    // System.exit(0); 
    System.out.println("Got tiaan!!!"); 
} 

該代碼等同於以下內容:

String output = Protocol.ProcessInput(input) 
if(output.equalsIgnoreCase("tiaan")){ 
    // System.exit(0); 
    System.out.println("Got tiaan!!!"); 
} 

所以從ProcessInput的輸出與字符串「tiaan」看着ProcessInput顯示,它永遠不會返回該字符串。因此,也許你真正想要做別的事,例如輸入比較直接與「tiaan」或改變ProcessInput實現:

if(input.equalsIgnoreCase("tiaan")){ 
    // System.exit(0); 
    System.out.println("Got tiaan!!!"); 
} 

注意,你可以得到一個NullPointerException當你讀輸入:

//Change this: 
String input = br.readLine().toString(); 
//Into this: 
String input = br.readLine(); 

readLine已經給你一個字符串,這樣你就不會在最後需要的toString。如果readLine給你空,當你到達流的末尾,這確實如此,那麼toString調用會導致一個NullPointerException。在下一行你實際檢查輸入是否爲空,這是好的,但使用你的代碼錯誤將發生在檢查之前。

+0

謝謝你,現在工作。 – tiaan3365