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

问题描述

我有一个 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 的 抛出的nofollow noreferrer">SocketTimeoutException/DatagramSocket.html#receive(java.net.DatagramPacket)" rel="nofollow noreferrer">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.

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

一个例子(w.r.t你的代码):

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 套接字的接收()的阻塞调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 16:20