本文介绍了向DatagramSocket添加超时 - receive()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在代码的这一部分上创建10秒超时
I need to create a 10 second timeout on this part of the code
我需要它列出10s的传入数据包它会在10s之前收到一个数据包,它会跳到if语句,如果它达到10s,它会跳转到else并重新发送数据包。这是可能的,我怎么能这样做,我对此很新。
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) {
}
}
推荐答案
这应该适用于你的例子。
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...
}
这篇关于向DatagramSocket添加超时 - receive()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!