2013-05-22 79 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