Adding timeout to DatagramSocket - receive()(向 DatagramSocket 添加超时-receive())
问题描述
我需要在这部分代码上创建一个 10 秒的超时时间
I need to create a 10 second timeout on this part of the code
DatagramPacket getack = new DatagramPacket(incoming, incoming.length);
socket.receive(getack);
DatagramPacket getack = new DatagramPacket(incoming, incoming.length);
socket.receive(getack);
我需要它列出 10 秒的传入数据包,如果它在 10 秒之前收到一个数据包,它将跳到 if 语句,以防它达到 10 秒,它会跳到 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:向 DatagramSocket 添加超时-receive()
基础教程推荐
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01