gpt4 book ai didi

java - 当数据包未从服务器发送时,如何在 UDP 客户端中设置超时?

转载 作者:行者123 更新时间:2023-11-29 07:37:05 24 4
gpt4 key购买 nike

我正在编写一个关于 UDP 套接字编程的简单程序。我正在使用数据报套接字。我必须将数据包从客户端发送到服务器。然后服务器随机决定是否发回数据包。客户端必须接受发送的数据包或等待 2 秒并假设数据包丢失。我无法处理数据包丢失的情况。

    System.out.println("Receiving message...");
dsock.receive(dpack); // receive the packet
System.out.println("Message received");

如果数据包已发送,一切正常,但我如何处理未发送数据包但我仍然有这行代码的情况?

最佳答案

您可以更改套接字的超时并接收消息,直到达到超时,如下所示:

try {
dsock = new DatagramSocket();
byte[] buf = new byte[1000];
DatagramPacket dpack = new DatagramPacket(buf, buf.length);

//...

dsock.setSoTimeout(1000); // set the timeout in millisecounds.

while(true) { // recieve data until timeout
try {
System.out.println("Receiving message...");
dsock.receive(dpack); // receive the packet
System.out.println("Message received");
}
catch (SocketTimeoutException e) {
// timeout exception.
System.out.println("Timeout reached!!! " + e);
dsock.close();
}
}
catch (SocketException e) {
System.out.println("Socket closed " + e);

}

关于java - 当数据包未从服务器发送时,如何在 UDP 客户端中设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34350728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com