Going through some tutorials about sockets, I keep coming across code like that:
while(true){
socket.receive(packet);
String message = new String(packet.getData(),0,packet.getLength(), TEXT_ENCODING);
System.out.println(message);
}
Question is: How is this loop left? Only via the catch, once receive() is done?
To be more precise, here’s what I’ve done:
while(true) {
try {
socket.receive(answer);
resultString = new String(answer.getData(), 0, answer.getLength(), "ASCII");
if (isMyIdentifier(resultString)) {
gatewayIP = answer.getAddress().getHostAddress();
return true;
} else {
return false;
}
}
catch (SocketTimeoutException e) {
throw new GatewayNotReachableException();
}
}
But I keep coming up with a timeoutexception, although the read is correct. So I was wondering, if the exception is the ‘expected’ way to leave. Although I seriously doubt that… ANd the socket.receive(packet) is, where the exception is thrown.
In the code below there is a continuous
while loop, which may seem a suitable implementation, however some servers have a tendency to keep listening, and handle the requests simultaneously.This while loop will never exit!