2010-01-18 63 views
-3

这是我的服务器类,它让客户端彼此聊天,但它会返回这条线的空指针异常:while (!(line = in.readLine()).equalsIgnoreCase("/quit"))你能帮我吗?谢谢。为什么它返回空指针异常(服务器端)

我ChatHandler类:

final static Vector handlers = new Vector(10); 
private Socket socket; 
private BufferedReader in; 
private PrintWriter out; 

public ChatHandler(Socket socket) throws IOException { 
    this.socket = socket; 
    in = new BufferedReader(
      new InputStreamReader(socket.getInputStream())); 
    out = new PrintWriter(
      new OutputStreamWriter(socket.getOutputStream())); 
} 

@Override 
public void run() { 
    String line; 

    synchronized (handlers) { 
     handlers.addElement(this); 
    // add() not found in Vector class 
    } 
    try { 
     while (!(line = in.readLine()).equalsIgnoreCase("/quit")) { 
      for (int i = 0; i < handlers.size(); i++) { 
       synchronized (handlers) { 
        ChatHandler handler = 
          (ChatHandler) handlers.elementAt(i); 
        handler.out.println(line + "\r"); 
        handler.out.flush(); 
       } 
      } 
     } 
    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } finally { 
     try { 
      in.close(); 
      out.close(); 
      socket.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      synchronized (handlers) { 
       handlers.removeElement(this); 
      } 
     } 
    } 
} 

客户端类的一部分:

String teXt = MainClient.getText(); 

    os.println(teXt); 
    os.flush(); 
    try { 
     String line = is.readLine(); 



      setFromServertext("Text recieved:"+line+"\n"); 

     is.close(); 
     is.close(); 
     c.close(); 
    } catch (IOException ex) { 
     Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex); 
    } 
+8

您发布关于'NullPointerException'的一些问题之前,你被告知如何在将来以聪明的方式提出问题,并且你也被相当高度地解释了如何调试和初始化根本原因。你有没有从中学到什么?例如,你看* in.readLine()可能会返回null,这样'.equalsIgnoreCase()'根本不起作用吗? – BalusC 2010-01-18 18:29:28

回答

3

这不是正确的idiom.The BufferedReader#readLine()将返回null到达流的末尾时。

因此,下面的

while (!(line = in.readLine()).equalsIgnoreCase("/quit")) { 
    // Do stuff. 
} 

不得不被替换为:

while ((line = in.readLine()) != null && !line.equalsIgnoreCase("/quit")) { 
    // Do stuff. 
} 

也看到Sun自己的基本的Java IO教程如何使用BufferedReaderhttp://java.sun.com/docs/books/tutorial/essential/io/

+0

我已经完成了你告诉我的所有事情,但是客户端从另一个客户端获得的文本仍然存在问题。我编辑了我的文章,并且为此添加了客户端,请帮助我。 – Johanna 2010-01-18 19:10:01

+0

NPE是否修复?我看到你已经创建了一个新的话题,证明你已经修复了NPE。 – BalusC 2010-01-18 19:50:28

+0

yes.it已经修复,非常感谢。 – Johanna 2010-01-18 20:04:12

2

in.readLine()将返回null时,有没有更多的阅读。你需要改变,要

String line; 
while ((line = in.readLine()) != null) { 
    if (!line.equalsIgnoreCase("/quit")) { 

    } 
} 
+0

她想做相反的事。当行不**时不等于'/ quit'。另请参阅我的答案。 – BalusC 2010-01-18 18:39:58

+0

@BalusC - 我做了改变。 – 2010-01-18 18:41:06

+0

哦,是的,我看到了,我的坏。 – 2010-01-18 20:05:21