Java Reference
In-Depth Information
Once you've joined a multicast group, you receive datagrams exactly as you receive
unicast datagrams, as shown in the previous chapter. That is, you set up a Datagram
Packet as a buffer and pass it into this socket's receive() method. For example:
try {
MulticastSocket ms = new MulticastSocket ( 4000 );
InetAddress ia = InetAddress . getByName ( "224.2.2.2" );
ms . joinGroup ( ia );
byte [] buffer = new byte [ 8192 ];
while ( true ) {
DatagramPacket dp = new DatagramPacket ( buffer , buffer . length );
ms . receive ( dp );
String s = new String ( dp . getData (), "8859_1" );
System . out . println ( s );
}
} catch ( IOException ex ) {
System . err . println ( ex );
}
If the address that you try to join is not a multicast address (if it is not between 224.0.0.0
and 239.255.255.255), the joinGroup() method throws an IOException .
A single MulticastSocket can join multiple multicast groups. Information about
membership in multicast groups is stored in multicast routers, not in the object. In this
case, you'd use the address stored in the incoming datagram to determine which address
a packet was intended for.
Multiple multicast sockets on the same machine and even in the same Java program can
all join the same group. If so, each socket receives a complete copy of the data addressed
to that group that arrives at the local host.
A second argument allows you to join a multicast group only on a specified local network
interface. For example, this code fragment attempts to join the group with IP address
224.2.2.2 on the network interface named “eth0”, if such an interface exists. If no such
interface exists, then it joins on all available network interfaces:
MulticastSocket ms = new MulticastSocket ();
SocketAddress group = new InetSocketAddress ( "224.2.2.2" , 40 );
NetworkInterface ni = NetworkInterface . getByName ( "eth0" );
if ( ni != null ) {
ms . joinGroup ( group , ni );
} else {
ms . joinGroup ( group );
}
Other than the extra argument specifying the network interface to listen from, this
behaves pretty much like the single-argument joinGroup() method. For instance, pass‐
ing a SocketAddress object that does not represent a multicast group as the first argu‐
ment throws an IOException .
Search WWH ::




Custom Search