Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding timeout to DatagramSocket - receive()

Tags:

I need to create a 10 second timeout on this part of the code

DatagramPacket getack = new DatagramPacket(incoming, incoming.length);
socket.receive(getack);

I need it to listed for incoming packets for 10s if it receives a packet before 10s it would skip down to if statement in case it reaches 10s it would jump down to else and resend the packet. Is this possible and how could i do this iam pretty new to this.

private static void sendDATA() {     outgoing = new byte[512]; // Empty array     try {         ByteBuffer sDATA = ByteBuffer.allocate(516);         // 512 - 2 byte opcode, 2 byte block #, 512 data          DatagramPacket data = new DatagramPacket(outgoing, outgoing.length, InetAddress.getByName(clientip), clientport);         InputStream fis = new FileInputStream(new File(FILE));          int a;         int block = 1;           while((a = fis.read(outgoing,0,512)) != -1)         {             data.setLength(a);             sDATA.put((byte)3);             sDATA.put((byte)block);             sDATA.put(outgoing);             socket.send(data);               while(true) {                 DatagramPacket getack = new DatagramPacket(incoming, incoming.length);                 socket.receive(getack);                  if(incoming[0] == 3 && incoming[1] == block) {                     break;                 } else {                     socket.send(data);                 }             }          }            } catch (Exception e) {      }  } 
like image 206
Sterling Duchess Avatar asked Sep 11 '12 05:09

Sterling Duchess


2 Answers

That should work for your example.

socket.setSoTimeout(10000); while(true) {     DatagramPacket getack = new DatagramPacket(incoming, incoming.length);     try {         socket.receive(getack);     } catch (SocketTimeoutException e) {        // resend        socket.send(data);        continue;     }     // check received data... } 
like image 62
sebastian Avatar answered Sep 22 '22 14:09

sebastian


socket.setSoTimeout(10000); socket.receive(getack); socket.setSoTimeout(0); 
like image 31
Bartosz Konkol Avatar answered Sep 19 '22 14:09

Bartosz Konkol