why it returns null pointer exception (server side )
this is my server class which let the clients to chat with each other but it will return nullpointer exception for this line: while (!(line = in.readLine()).equalsIgnoreCase("/quit"))
would you please help me?thanks.
my ChatHandler class:
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 开发者_JS百科{
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
synchronized (handlers) {
handlers.removeElement(this);
}
}
}
}
a part of client class:
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);
}
This isn't the correct idiom.The BufferedReader#readLine()
will return null
when end of stream is reached.
Thus, the following
while (!(line = in.readLine()).equalsIgnoreCase("/quit")) {
// Do stuff.
}
has to be replaced by:
while ((line = in.readLine()) != null && !line.equalsIgnoreCase("/quit")) {
// Do stuff.
}
Also see Sun's own basic Java IO tutorials how to use a BufferedReader
: http://java.sun.com/docs/books/tutorial/essential/io/
in.readLine()
will return null
when there is nothing more to read. You need to change that to
String line;
while ((line = in.readLine()) != null) {
if (!line.equalsIgnoreCase("/quit")) {
}
}
精彩评论