4
I created the class Server
! However an Exception of the type is launched java.lang.NullPointerException
! I wonder if someone could help me with this problem?
The class is as follows:
public class Server {
public static final int SERVERPORT = 8888;
public static void main(String[] args) throws IOException {
System.out.println("Starting echo server...");
ServerSocket ss = new ServerSocket(SERVERPORT);
boolean condition = true;
while (condition)
{
Socket s = ss.accept();
try
{
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String msg = br.readLine();
boolean condition1 = true;
while (condition1) {
System.out.println(msg);
msg = br.readLine();
if(msg.equals("quit")){
condition1=false;
}
}
if(msg.equals("quit")){
condition=false;
}
}
catch (IOException ioe)
{
System.err.println("I/O error: " + ioe.getMessage());
}
finally
{
try
{
s.close();
}
catch (IOException ioe)
{
assert false;
}
}
}
}
}
Where the error comes?
– Maniero
The error points to the following statement: if(msg.equals("quit"))
– MarcoAF
@Marcoaf If the stream content ends before the message
quit
arrive, thebr.readLine()
will returnnull
. There’s not much of a way out except test it out... (or make sure there’s never gonna miss thequit
at the end) P.S. You read the message, print it on the screen, then read it again - how to know if the first message received was not quit?– mgibsonbr
I won’t be able to help you but since I’ve modified the code so I can better understand the hint of a logic without flags. http://ideone.com/aiXooY
– Maniero
@bigown -> http://meta.pt.stackoverflow.com/questions/2333/por-que-muitas-peoples-respondsnos-coment%C3%A1rios-in-place-to-create-a-response - the tip :)
– Victor Stafusa
@Victor doesn’t believe this answers the question. I don’t have Java here to test correctly.
– Maniero