简体   繁体   English

如何知道我们是否收到过DatagramPacket的东西?

[英]how to know if we have received something with a DatagramPacket or not?

I'm implementing a client-server program, and wanted that my client, after waiting 5 seconds without an ACK-Answer from server, sends back the same packet... 我正在实现一个客户端 - 服务器程序,并希望我的客户端在等待5秒后没有来自服务器的ACK-Answer后,发送回相同的数据包......

I made it like this, so please tell me if it's okay.. 我是这样做的,所以请告诉我它是否可以..

dp = new DatagramPacket(packet , packet.length , host , port);
        sock.send(dp);
        time = System.currentTimeMillis();
        while ((System.currentTimeMillis() - time < 5000) && ack_dp.getLength() == 0) {
            sock.receive(ack_dp);
        }

        if (ack_dp.getLength() == 0)
            sock.send(dp);

so my program will wait 5 second of the ACK, if he doesnt receive anything, he will resend the same packet. 所以我的程序将等待5秒的ACK,如果他没有收到任何东西,他将重新发送相同的数据包。 I check if he received an ack or not with the packet length.. if it stays 0, then he hasnt received anything.. if it will be longer than 0, then out of the while-sequence and send a new packet.. (ps: ack_dp is 2bytes) 我检查他是否收到了包长度的确认..如果它保持为0,那么他没有收到任何东西..如果它会超过0,那么在时间序列之外并发送一个新数据包..( ps:ack_dp是2字节)

receive() on the socket will by default block, so your loop doesn't make sense here (even if the socket was set to non-blocking, it's a Bad Idea TM to busy-wait in 99.99% of the cases). 默认情况下,套接字上的receive()会被阻塞,所以你的循环在这里没有意义(即使套接字被设置为非阻塞,在99.99%的情况下忙于等待是一个坏主意TM )。

Use setSoTimeout() , and catch SocketTimeoutException instead. 使用setSoTimeout() ,并捕获SocketTimeoutException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM