I have a working multicast receiver on my Android enabled dev board (version 4.3) using MulticastSocket; what I want instead is to be able to use NIO channels. With MulticastChannel not existing in Android, I have tried to use DatagramChannel in its place without any luck thus far. If anyone has any information about configuring the channel to do multicast reception only, that would be awesome!
Heres some sample code that does not work, but will give a general idea about how I'm doing the set-up:
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);
Yields this (which I kind of expected):
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
Working code. _pairChannelAndSocket() method
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With