Java Reference
In-Depth Information
To send and receive multicast data beyond the local subnet, you need a multicast router.
Check with your network administrator to see whether your routers support multi‐
casting. You can also try pinging
all-routers.mcast.net
. If any router responds, then your
network is hooked up to a multicast router:
%
ping all-routers.mcast.net
all-routers.mcast.net is alive
This still may not allow you to send to or receive from every multicast-capable host on
the Internet. For your packets to reach any given host, there must be a path of multicast-
capable routers between your host and the remote host. Alternatively, some sites may
be connected by special multicast tunnel software that transmits multicast data over
unicast UDP that all routers understand. If you have trouble getting the examples in
this chapter to produce the expected results, check with your local network adminis‐
trator or ISP to see whether multicasting is actually supported by your routers.
Working with Multicast Sockets
Enough theory. In Java, you multicast data using the
java.net.MulticastSocket
class,
a subclass of
java.net.DatagramSocket
:
public
class
MulticastSocket
extends
DatagramSocket
implements
Closeable
,
AutoCloseable
As you would expect,
MulticastSocket
's behavior is very similar to
DatagramSocket
's:
you put your data in
DatagramPacket
objects that you send and receive with the
Mul
ticastSocket
. Therefore, I won't repeat the basics; this discussion assumes that you
already know how to work with datagrams. If you're jumping around in this topic rather
than reading it cover to cover, now might be a good time to go back and read
Chapter 12
.
To receive data that is being multicast from a remote site, first create a
MulticastSock
et
with the
MulticastSocket()
constructor. As with other kinds of sockets, you need
to know the port to listen on. This code fragment opens a
MulticastSocket
that listens
on port 2300:
MulticastSocket
ms
=
new
MulticastSocket
(
2300
);
Next, join a multicast group using the
MulticastSocket
's
joinGroup()
method:
InetAddress
group
=
InetAddress
.
getByName
(
"224.2.2.2"
);
ms
.
joinGroup
(
group
);
This signals the routers in the path between you and the server to start sending data
your way and tells the local host that it should pass you IP packets addressed to the
multicast group.
Once you've joined the multicast group, you receive UDP data just as you would with
a
DatagramSocket
. You create a
DatagramPacket
with a byte array that serves as a buffer