这是我的服务器类,它允许客户端相互聊天,但它会返回此行的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);
}
}
}
}
客户端类的一部分:
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);
}
答案 0 :(得分:3)
这不是正确的习惯用法。当到达流的末尾时,BufferedReader#readLine()
将返回null
。
因此,以下
while (!(line = in.readLine()).equalsIgnoreCase("/quit")) {
// Do stuff.
}
必须替换为:
while ((line = in.readLine()) != null && !line.equalsIgnoreCase("/quit")) {
// Do stuff.
}
另请参阅Sun自己的基本Java IO教程,了解如何使用BufferedReader
:http://java.sun.com/docs/books/tutorial/essential/io/
答案 1 :(得分:2)
in.readLine()
将返回null
。您需要将其更改为
String line;
while ((line = in.readLine()) != null) {
if (!line.equalsIgnoreCase("/quit")) {
}
}