编程语言
首页 > 编程语言> > java-在Android中使用DatagramChannel进行多播数据

java-在Android中使用DatagramChannel进行多播数据

作者:互联网

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

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

InetAddress groupAddr = InetAddress.getByName(groupAddress);
SelectorProvider provider = SelectorProvider.provider();
Selector selector = provider.openSelector();    
DatagramChannel dc = DatagramChannel.open();
// this cast fails
MulticastSocket socket = (MulticastSocket) dc.socket();
// set ttl
socket.setTimeToLive(16);
// set receive buffer
socket.setReceiveBufferSize(65536);
socket.setReuseAddress(true);
// join group
socket.joinGroup(groupAddr);

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

11-14 18:11:56.203: E/AndroidRuntime(22315): FATAL EXCEPTION: DatagramListener
11-14 18:11:56.203: E/AndroidRuntime(22315): java.lang.ClassCastException: java.nio.DatagramChannelImpl$DatagramSocketAdapter cannot be cast to 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);
        }
    }
}

标签:java,android,multicast
来源: https://codeday.me/bug/20191122/2060214.html