简体   繁体   English

如果长时间不活动,java.net.DatagramSocket将等待客户端请求多少时间?

[英]how much time java.net.DatagramSocket will wait for a client request if inactive for long time?

I am experiencing problems when using a UDP datagram packet, in the program I bind a UDP port and listen messages on it. 使用UDP数据报包时遇到问题,我在程序中绑定了UDP端口并在其上侦听消息。 This normally works fine, but if the port remains idle for a long time, the program automatically terminates the UDP socket. 这通常可以正常工作,但是如果端口长时间保持空闲状态,则程序会自动终止UDP套接字。 Unfortunately, the log file is huge and it is difficult to find the exception. 不幸的是,日志文件很大,很难找到异常。 Please help me find a way to keep the UDP port alive forever. 请帮助我找到一种使UDP端口永久存活的方法。 Thanks in advance. 提前致谢。

Here is my code: 这是我的代码:

socket = new DatagramSocket(port);
setBindSocket(true);            
socket.setSoTimeout(60000);

while(isBindSocket()) {
    try {               

        byte[] buffur = new byte[512];              
        DatagramPacket inputPacket = new DatagramPacket(buffur, buffur.length);
        inputPacket.setLength(buffur.length);
        socket.receive(inputPacket);
        byte [] bString = inputPacket.getData();
        String hString = new String(bString);        

    } catch (SocketTimeoutException ste) {
    } catch (Exception e) { 
        e.printStackTrace();
    }
}

The following statement changes the socket's behavior when receiving - if no datagram arrives in 60 seconds, a SocketTimeoutException is thrown. 以下语句更改了接收时套接字的行为-如果60秒钟内没有数据报到达,则抛出SocketTimeoutException。

socket.setSoTimeout(60000);

Maybe I have misunderstood your question. 也许我误解了你的问题。

You're going to have to find that exception. 您将必须找到该异常。 Unless you set a read timeout, the read method will block forever. 除非您设置读取超时,否则read方法将永远阻塞。

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

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