How would an example of using a Java 7 NIO.2 multicast client look like? I could only find half of an example in the MulticastChannel documentation.
Asked
Active
Viewed 4,074 times
1 Answers
4
This example works. Note that DatagramChannel.join()
requires a NetworkInterface
to work.
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
InetAddress group = InetAddress.getByName("239.255.0.1")
DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
.setOption(StandardSocketOptions.SO_REUSEADDR, true)
.bind(new InetSocketAddress(5000))
.setOption(StandardSocketOptions.IP_MULTICAST_IF, ni);
MembershipKey key = dc.join(group, ni);
ByteBuffer byteBuffer = ByteBuffer.allocate(1500);
while (true) {
if (key.isValid()) {
byteBuffer.clear();
InetSocketAddress sa = (InetSocketAddress) dc.receive(byteBuffer);
byteBuffer.flip();
System.out.println("Multicast received from " + sa.getHostString());
// TODO: Parse message
}
}

Sundae
- 724
- 1
- 8
- 27
-
is multicast supported by of majority hardware? What if doesn't? – Ivan Voroshilin Mar 03 '14 at 13:43
-
Whether multicast works or not depends on the underlying network stack. I guess that DatagramChannel.join() should throw an exception if the system doesn't support multicast, but that may be implementation specific. – Sundae Mar 04 '14 at 14:15
-
Thanks Sundae for this minimally concise (blocking) nio example - exactly what the doctor ordered! +1 – Evgeniy Berezovsky Oct 20 '15 at 06:57