Java 为什么返回空指针异常(服务器端)

Java 为什么返回空指针异常(服务器端),java,networking,Java,Networking,这是我的服务器类,它允许客户端彼此聊天,但它将返回这一行的nullpointer异常:while!line=in.readLine.equalsIgnoreCase/quit你能帮我吗?谢谢 我的ChatHandler类: final static Vector handlers = new Vector(10); private Socket socket; private BufferedReader in; private PrintWriter out; public ChatHan

这是我的服务器类,它允许客户端彼此聊天,但它将返回这一行的nullpointer异常: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);
            }
        }
    }
}
当没有更多内容可读取时,in.readLine将返回null。你需要把它改成

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

    }
}

这不是正确的习惯用法。到达流结束时,BufferedReaderreadLine将返回null

因此,以下

while (!(line = in.readLine()).equalsIgnoreCase("/quit")) {
    // Do stuff.
}
必须替换为:

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

另请参阅Sun自己的基本Java IO教程“如何使用BufferedReader:

您以前曾发布过一些有关NullPointerException的问题,他们告诉您将来如何以智能方式提问,并且还向您解释了如何调试和确定根本原因。你从中学到什么了吗?例如,您是否看到in.readLine可能会返回null,因此.equalsIgnoreCase根本不起作用?她想做相反的事情。当行不相等/退出时。另请看我的答案。@BalusC-我已经做了更改。我已经按照你的要求做了。但是客户端从另一个客户端获得的文本仍然存在问题。我已经编辑了我的帖子,并为此添加了客户端,请帮我谢谢。NPE是否已修复?我看到你已经创建了一个新主题,证明你已经修复了NPE。
while ((line = in.readLine()) != null && !line.equalsIgnoreCase("/quit")) {
    // Do stuff.
}