我需要在代码的这一部分上创建10秒的超时时间
如果它在10s之前收到数据包,我需要列出10s的传入数据包,如果它到达10s,它将跳至if语句,如果到达10s,它将跳至else并重新发送数据包。这可能吗,我该怎么做呢?
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) {
}
}
最佳答案
这应该适合您的示例。
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...
}