可选多播套接字(1.7 之前的版本)
随着 NIO 的出现,大多数套接字类型都可以通过 SelectableChannel 实现“选择”。不幸的是,DatagramChannel 在 java 7 之前不支持多播。在之前的版本中通过 MulticastSocket
类支持多播。
我想要某种方法能够检测多播数据报套接字上是否有挂起的消息(即可读)消息。我想阅读,直到立即时间窗口内没有剩余的数据报。收到所有待处理消息后,然后想要调用回调,但不是单独调用或在读取所有待处理消息之前调用回调。
为了让事情变得更简单,我们假设一个套接字。在伪代码中:
List<Msg> received = new ArrayList<Msg>
while (true)
{
received.clear();
// initial blocking receive
data = receive_blocking (socket, datagram)
received.add (new Msg(data));
// flush out remaining messages
for (boolean receiving = true ; receiving ; )
{
// non-blocking
if (receive_nonblocking (socket, datagram))
received.add (new Msg(datagram));
else
receiving = false;
}
callback (received);
}
问题是如何在没有 NIO 2 的情况下实现 receive_nonblocking 。我不需要选择器机制,但想知道是否有某种方法可以进行非阻塞读取或其他方式检测是否有待处理的事情。
我读过要使用选择器,必须像 new DatagramChannel() 中那样直接创建通道,而不是在创建套接字后获取通道。因此,如果正确,则无法使用 socket.getChannel()
在创建套接字后创建选择器。
有没有什么方法可以做到这一点,不涉及 JNI 或计时器,在 java 7 之前?
With the advent of NIO most socket types could be "selectable" through the SelectableChannel implementation. Unfortunately the DatagramChannel does not support multicast prior to java 7. Multicast is supported in prior versions via the MulticastSocket
class.
I want some way to be able to detect that there are pending messages (i.e. readable) messages on a multicast datagram socket. I would like to read until there are no remaining datagrams within the immediate time window. Having received all pending messages, then want to invoke a callback, but not individually or prior to having read all pending messages.
Making this simpler, let's assume one socket. In pseudo code:
List<Msg> received = new ArrayList<Msg>
while (true)
{
received.clear();
// initial blocking receive
data = receive_blocking (socket, datagram)
received.add (new Msg(data));
// flush out remaining messages
for (boolean receiving = true ; receiving ; )
{
// non-blocking
if (receive_nonblocking (socket, datagram))
received.add (new Msg(datagram));
else
receiving = false;
}
callback (received);
}
The question is how to implement receive_nonblocking
without NIO 2. I do not need the Selector mechanism, but wondering whether there is some way I can do a non-blocking read(s) or otherwise detect whether there is something pending.
I had read that to use the selector, the channels must be created directly as in new DatagramChannel()
, rather than acquiring a channel after socket creation. So if am correct, could not use the socket.getChannel()
to create a selector post socket creation.
Is there any way to do this that doesn't involve JNI or timers, pre java 7?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需设置一个非常短的读取超时时间,并捕获 SocketTimeoutException(到期时将抛出该异常),并跳出读取循环。
Just set a very short read timeout, and catch SocketTimeoutException, which will be thrown when it expires, and break out of your reading loop.