Java Reference
In-Depth Information
chosen, as well as a multicasting IP address. The group or registered listeners will use
the IP address in order to listen for broadcasts. The port number must not be in use or
an exception will be thrown. For IPv4 multicasting, the IP address must range from
224.0.0.0 to 239.255.255.255, inclusive. This port and IP address is the same one used
by a server to broadcast the message. Next, a new DatagramChannel is opened us-
ing StandardProtocolFamily.INET . The choices for opening a Data-
gramChannel are StandardProtocolFamily.INET or StandardProto-
colFamily.INET6 , corresponding to IPv4 and IPv6, respectively. The first option
that is set on the DatagramChannel is StandardSocketOp-
tions.SO_REUSEADDR , and it is set to true . This indicates that multiple clients
will be able to “reuse” the address or use it at the same time. This needs to be set for a
multicast to occur. The client is then bound to the port using a new InetSocketAd-
dress instance. Last, the StandardSocketOptions.IP_MULTICAST_IF op-
tion is set to the network interface that is used. This option represents the outgoing in-
terface for multicast datagrams sent by the datagram-oriented socket.
client.setOption(StandardSocketOptions.SO_REUSEADDR,
true);
client.bind(new InetSocketAddress(port));
client.setOption(StandardSocketOptions.IP_MULTICAST_IF,
networkInterface);
Once these options have been set and the port has been bound to the Data-
gramChannel , it is ready to join the group of listeners. This can be done by calling
the DatagramChanneljoin(InetAddress, NetworkInterface) method,
passing the group address and network interface that will be used by the client. As a
result, a java.nio.channels.MembershipKey object is produced, which is a
token that represents the membership of an IP multicast group. Last, the Data-
gramChannelopen() method is called, which opens the channel to listen for broad-
casts. At this point, the client is ready to receive multicast messages and it waits for a
message to be received.
MembershipKey key = client.join(group, networkInterface);
client.open();
The next lines of code in the client take care of receiving messages from the server.
In order to receive a broadcasted message, a ByteBuffer is created and then eventu-
ally passed to the DatagramChannel 's receive() method. Once the re-
Search WWH ::




Custom Search