2010-01-18 68 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