protected abstract DatagramChannelFactory newServerSocketChannelFactory(Executor executor);
protected abstract DatagramChannelFactory newClientSocketChannelFactory(Executor executor);
@Test
public void testMulticast() throws Throwable {
ConnectionlessBootstrap sb = new ConnectionlessBootstrap(
newServerSocketChannelFactory(Executors.newCachedThreadPool()));
ConnectionlessBootstrap cb = new ConnectionlessBootstrap(
newClientSocketChannelFactory(Executors.newCachedThreadPool()));
DatagramChannel sc = null;
DatagramChannel cc = null;
try {
MulticastTestHandler mhandler = new MulticastTestHandler();
cb.getPipeline().addFirst("handler", mhandler);
sb.getPipeline().addFirst("handler", new SimpleChannelUpstreamHandler());
int port = TestUtil.getFreePort();
NetworkInterface loopbackIf;
try {
loopbackIf = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
} catch (SocketException e) {
loopbackIf = null;
}
// check if the NetworkInterface is null, this is the case on my ubuntu dev machine but not on osx and windows.
// if so fail back the the first interface
if (loopbackIf == null) {
for (Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
e.hasMoreElements();) {
NetworkInterface nif = e.nextElement();
if (nif.isLoopback()) {
loopbackIf = nif;
break;
}
}
}
sb.setOption("networkInterface", loopbackIf);
sb.setOption("reuseAddress", true);
sc = (DatagramChannel) sb.bind(new InetSocketAddress(port));
String group = "230.0.0.1";
InetSocketAddress groupAddress = new InetSocketAddress(group, port);
cb.setOption("networkInterface", loopbackIf);
cb.setOption("reuseAddress", true);
cc = (DatagramChannel) cb.bind(new InetSocketAddress(port));
assertTrue(cc.joinGroup(groupAddress, loopbackIf).awaitUninterruptibly().isSuccess());
assertTrue(sc.write(wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess());
assertTrue(mhandler.await());
assertTrue(sc.write(wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess());
// leave the group
assertTrue(cc.leaveGroup(groupAddress, loopbackIf).awaitUninterruptibly().isSuccess());
// sleep a second to make sure we left the group
Thread.sleep(1000);
// we should not receive a message anymore as we left the group before
assertTrue(sc.write(wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess());
} finally {
if (sc != null) {
sc.close().awaitUninterruptibly();
}
if (cc != null) {
cc.close().awaitUninterruptibly();
}
sb.releaseExternalResources();
cb.releaseExternalResources();
}
}