且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何中断对UDP套接字的receive()的阻塞调用

更新时间:2023-11-14 15:23:46

您需要使用socket的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
}