Canyonman133 Canyonman133 - 7 months ago 19
Java Question

While true loop being broken by a try/catch in Java

I am a beginner to networking and am working on implementing it in a game i have, it is mostly working but in the client my loop receiving packets is stopping ant a try catch. here is the code:

public void run() {
while(true){
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
}catch(IOException e){
e.printStackTrace();
}

this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
}
}


After debugging i have found that the loop is not getting past the try catch statement.(but the try is being activated once seemingly with no error).

Answer

As per java-docs for the method public void receive(DatagramPacket p)

This method blocks until a datagram is received.

The thread executing the flow gets blocked [waits until the datagram is received]. Your loop is not broken its just in halt state. Loop will be broken in case of some exception occurs which is not caught and handled in side the body of the loop.