Joza100
Joza100

Reputation: 356

Java Networking Blocking methods and while loop

I made a simple UDP server/client system for my game now. This is the code of the method that waits for data to be sent to it:

while (handler.isRunning()) {
    byte[] data = new byte[1024];
    DatagramPacket packet = new DatagramPacket(data,   data.length);
    try {
        socket.receive(packet);
    } catch (IOException e) {
         e.printStackTrace();
    }
    System.out.println("Server - " + new String(data).trim());

}
socket.close(); 

So, the thing is, when the game closes meaning that isRunning() gets set to false, all threads die except the server and client. The reason is because here, socket.receive() method blocks and it needs to receive at least one more packet to then check if isRunning() is true and exit. So after I close the game, I want this thread to die immediately without receiving anymore packets, but i dont know how to do that! Thanks for help

Upvotes: 0

Views: 86

Answers (2)

ichantz
ichantz

Reputation: 298

Answered here. Similar for your case for DatagramSocket.receive

Upvotes: 1

Jonathan S. Fisher
Jonathan S. Fisher

Reputation: 8876

There's a couple of options. First, the simplest option is to set a timeout: https://docs.oracle.com/javase/7/docs/api/java/net/DatagramSocket.html#setSoTimeout(int).

Next, another option is to use callbacks and Async I/O. Take a look at java.nio.channels.DatagramChannel

Upvotes: 2

Related Questions