2010-01-18 3 views
-3

이것은 클라이언트가 서로 채팅 할 수있게 해주는 내 서버 클래스이지만 while (!(line = in.readLine()).equalsIgnoreCase("/quit")) 도와 주시겠습니까? 감사합니다.null 포인터 예외 (서버 측)를 반환하는 이유

내 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()'은'.equalsIgnoreCase()'가 전혀 작동하지 않도록'null'을 반환 할 수 있습니다. – BalusC

답변

3

에이 스트림의 끝에 도달하면 null를 반환합니다 올바른 idiom.The BufferedReader#readLine() 아님을 변경해야합니다. 따라서

다음

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

로 대체 할 수 있습니다 또한 사용하는 방법 일 자신의 기본적인 자바 IO 자습서를 참조

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

BufferedReader : http://java.sun.com/docs/books/tutorial/essential/io/

+0

나는 당신이 나에게 말한 것을 해냈다.하지만 여전히 클라이언트가 다른 클라이언트로부터 얻은 텍스트에 문제가있다. 나는 나의 포스트를 편집했고 클라이언트 쪽을 추가했다. 덕분에 도와 줘. – Johanna

+0

NPE가 고정되어 있습니까? NPE가 고정되어 있다는 것을 증명하는 새로운 주제를 이미 만들었습니다. – BalusC

+0

예. 고침을 고쳤습니다. 고맙습니다. 답변. – Johanna

2

in.readLine()null를 반환합니다. 당신은

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

    } 
} 
+0

그녀는 그 반대를 원했습니다. 줄이 ** 같지 않을 때 /'quit'. 또한 내 대답을 참조하십시오. – BalusC

+0

@BalusC - 변경했습니다. –

+0

오, 그래, 나도 안다. –

관련 문제