如何中断对UDP套接字的receive()的阻塞调用 [英] How to interrupt a blocking call to UDP socket's receive()

查看:584
本文介绍了如何中断对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.

推荐答案

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆