我需要在这部分代码上创建 10 秒超时
DatagramPacket getack = new DatagramPacket(incoming, incoming.length);
socket.receive(getack);
我需要它列出 10 秒的传入数据包,如果它在 10 秒之前收到一个数据包,它将跳到 if 语句,以防它达到 10 秒,它会跳到 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) {
}
}