简体   繁体   中英

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).

First of all your loop condition that you provided is not a variable , You have directly used a boolean valued true . It might a situation of infinite-loop .

 while(true){..... // yourCode ....}

Your loop will continue even if socket.receive(packet); line raise an IOException because this exception is handled by the catch() block.

it means it will execute till any exception raised at this line

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

Now, Your problem is this method public void receive(DatagramPacket p) actually method will work till datagram is received but your loop will continue till exception is raised till this.parsePacket() method raised an Exception.

So, please change your conditional statement such that if datagram is no more present then loop must be terminated.

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.

Also there is little suggestion I would like you to implement in your code. You should not run an infinite loop. Instead of using true you can try using Thread.currentThread().isInterrupted() and when your game ends you can call interrupt() on the Thread responsible for executing the code flow of the loop. Also if in case of IOException you wish to retry (may be in retry resources are in order and you do not get the exception) then putting catch inside the loop is OK else you can move the catch outside the loop, it depends on your need and flow. You can probably put a counter for number of retries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM