简体   繁体   English

Java-接收UDP数据包时设置tiimeout函数

[英]Java-Setting a tiimeout function when receiving a UDP packet java

Im trying to send a UDP packet and then wait for a response back from the server for 2 seconds. 我试图发送UDP数据包,然后等待服务器返回2秒钟的响应。 If my socket does not receive a packet back from the server in this time, then I will have to send the same packet back again. 如果我的套接字这次没有收到来自服务器的数据包,那么我将不得不再次发送相同的数据包。 I want the program to stop sending packets after it has sent 5 and then declare that the server is down. 我希望程序在发送5之后停止发送数据包,然后声明服务器已关闭。

Here is what I have, but I keep getting the error: 这是我所拥有的,但是我不断收到错误消息:

Exception in thread "main" java.net.SocketTimeoutException: Receive timed out 线程“主”中的异常java.net.SocketTimeoutException:接收超时

    clientSock.send(UDP_Packet);
    int count=0;
    while(count <5){
        try{
            clientSock.recieve(incomingPacket);
            clientSock.setSoTimeout(2000);
        } catch (SocketException e) {
            clientSock.send(UDP_Packet);
            count++;
            if(count>=5){
            System.out.println("Server is Down");
            }
        }
    }

Can someone tell me what I am doing wrong here or how to implement it? 有人可以告诉我我在这里做错什么或如何执行吗?

Thank you for your time 感谢您的时间

Well you need to set the timeout before doing the receive, not afterwards, but the main issue is that you're catching the wrong exception. 好了,您需要执行接收之前 (而不是之后)设置超时,但是主要问题是您正在捕获错误的异常。 You should be catching SocketTimeoutException . 您应该捕获SocketTimeoutException

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

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