我需要在这部分代码上创建一个10秒的超时
DatagramPacket getack =新的DatagramPacket(传入,incoming.length);
Socket.receive(获取确认);
我需要它为10s的传入数据包列出,如果它在10s之前收到一个数据包,它将跳到if语句,如果它达到10s,它将跳到否则,并重新发送数据包。这是可能的吗?我怎么做?我对此还很陌生。
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) {
}
}
发布于 2012-09-11 13:49:21
这应该适用于您的示例。
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...
}
发布于 2014-12-09 16:00:01
socket.setSoTimeout(10000);
socket.receive(getack);
socket.setSoTimeout(0);
https://stackoverflow.com/questions/12363078
复制相似问题