这是我的服务器类,它让客户端彼此聊天,但它会返回这条线的空指针异常: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);
}
您发布关于'NullPointerException'的一些问题之前,你被告知如何在将来以聪明的方式提出问题,并且你也被相当高度地解释了如何调试和初始化根本原因。你有没有从中学到什么?例如,你看* in.readLine()可能会返回null,这样'.equalsIgnoreCase()'根本不起作用吗? – BalusC 2010-01-18 18:29:28