我使用MulticastSocket在启用Android的开发板(版本4.3)上有一个工作正常的多播接收器;我想要的是能够使用NIO通道。在Android中不存在MulticastChannel的情况下,我尝试使用DatagramChannel代替它,但到目前为止没有任何运气。如果有人知道有关将通道配置为仅进行多播接收的信息,那就太好了!

以下是一些无效的示例代码,但会给出有关我如何进行设置的一般思路:

InetAddress groupAddr = InetAddress.getByName(groupAddress);
SelectorProvider provider = SelectorProvider.provider();
选择器选择器= provider.openSelector();
DatagramChannel dc = DatagramChannel.open();
//此强制转换失败
MulticastSocket socket =(MulticastSocket)dc.socket();
//设置ttl
socket.setTimeToLive(16);
//设置接收缓冲区
socket.setReceiveBufferSize(65536);
socket.setReuseAddress(true);
// 加入组
socket.joinGroup(groupAddr);

产生这个(我有点期望):

11-14 18:11:56.203:E / AndroidRuntime(22315):致命异常:DatagramListener
11-14 18:11:56.203:E / AndroidRuntime(22315):java.lang.ClassCastException:java.nio.DatagramChannelImpl $ DatagramSocketAdapter无法转换为java.net.MulticastSocket

最佳答案

工作代码。 _pairChannelAndSocket()方法

public class Sample
{
    private DatagramChannel createChannel(NetworkInterface networkIf, InetSocketAddress address)
            throws IOException {

        MulticastSocket socket = new MulticastSocket(address.getPort());
        socket.setReuseAddress(true);
        socket.setBroadcast(true);
        socket.joinGroup(MCAST_ADDRESS, networkIf);

        DatagramChannel channel = DatagramChannel.open();
        _pairChannelAndSocket(channel, socket);
        channel.configureBlocking(false);
        return channel;
    }

    public static void _pairChannelAndSocket(DatagramChannel channel, MulticastSocket socket) {
        try {
            Field f = channel.getClass().getDeclaredField("socket");
            f.setAccessible(true);
            f.set(channel, socket);
        } catch (Exception e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
}

10-07 16:14