user445338
user445338

Reputation:

How can I make reading from a DatagramSocket only block for a limited time (time out)?

I'm running a simulation for network packet transmission loss. My server app sometimes doesn't send data back to my client.

In my client I'm running a ping to the server every seconds 10 times. However, in the case where my server doesn't send anything back, my client will wait just wait until the next packet is received. How can I continue to the next iteration if I don't get anything from the server?

//attempt to read from server
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    receivePacket.getData();

//client blocks on this line until something is received from server
    clientSocket.receive(receivePacket);
    String receivedFromServer = new String(receivePacket.getData());
    System.out.println("FROM SERVER:" + receivedFromServer);

Upvotes: 1

Views: 1299

Answers (1)

mre
mre

Reputation: 44240

You'll want to set a timeout:

clientSocket.setSoTimeout(TIMEOUT_IN_MILLISECONDS)

Upvotes: 3

Related Questions