本文介绍了如何中断对UDP套接字的receive()的阻塞调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UDP服务器,侦听来自客户端的数据包.

I have a UDP server listening packets from a client.

socket = new DatagramSocket(port);

while (isListen) {
    byte[] data = new byte[1024];
    DatagramPacket packet = new DatagramPacket(data, 0, data.length);
    socket.receive(packet);
}

receive()方法将永远等待,直到接收到数据包.是否可以停止等待接收?我可以设置boolean isListen来停止循环.另一方面,如果套接字正在等待,那么如果客户端未发送任何数据包,它将永远等待.

The receive() method will wait forever before a packet received. Is it possible to stop waiting for receiving? I can set a boolean isListen to stop the loop. On the other hand, if the socket is waiting then it will wait forever if no packet send from the client.

推荐答案

您需要使用 setSoTimeout()方法并捕获socket的 receive() 方法(超过超时时间).捕获异常后,您可以继续使用套接字接收数据包.因此,在循环中利用该方法可以使您(根据超时设置)定期中断" receive()方法调用.

You need to set a socket timeout with the setSoTimeout() method and catch SocketTimeoutException thrown by the socket's receive() method when the timeout's been exceeded. After catching the exception you can keep using the socket for receiving packets. So utilizing the approach in a loop allows you to periodically (according to the timeout set) "interrupt" the receive() method call.

请注意,必须在进入阻止操作之前启用超时.

一个示例(没有您的代码):

An example (w.r.t your code):

socket = new DatagramSocket(port);
socket.setSoTimeout(TIMEOUT_IN_MILLIS)

while (isListen) {
    byte[] data = new byte[1024];
    DatagramPacket packet = new DatagramPacket(data, 0, data.length);

    while (true) {
        try {
            socket.receive(packet);
            break;
        } catch (SocketTimeoutException e) {
            if (!isListen) {} // implement your business logic here
        }
    }
    // handle the packet received
}

这篇关于如何中断对UDP套接字的receive()的阻塞调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 16:20