Java Reference
In-Depth Information
for data and enter a loop in which you receive the data by calling the
receive()
method
inherited from the
DatagramSocket
class:
byte
[]
buffer
=
new
byte
[
8192
];
DatagramPacket
dp
=
new
DatagramPacket
(
buffer
,
buffer
.
length
);
ms
.
receive
(
dp
);
When you no longer want to receive data, leave the multicast group by invoking the
socket's
leaveGroup()
method. You can then close the socket with the
close()
method
inherited from
DatagramSocket
:
ms
.
leaveGroup
(
group
);
ms
.
close
();
Sending data to a multicast address is similar to sending UDP data to a unicast address.
You do not need to join a multicast group to send data to it. You create a new
Datagram
Packet
, stuff the data and the address of the multicast group into the packet, and pass
it to the
send()
method:
InetAddress
ia
=
InetAddress
.
getByName
(
"experiment.mcast.net"
);
byte
[]
data
=
"Here's some multicast data\r\n"
.
getBytes
(
"UTF-8"
);
int
port
=
4000
;
DatagramPacket
dp
=
new
DatagramPacket
(
data
,
data
.
length
,
ia
,
port
);
MulticastSocket
ms
=
new
MulticastSocket
();
ms
.
send
(
dp
);
There is one caveat to all this: multicast sockets are a security hole big enough to drive
a small truck through. Consequently, untrusted code running under the control of a
SecurityManager
is not allowed to do anything involving multicast sockets. Remotely
loaded code is normally only allowed to send datagrams to or receive datagrams from
the host it was downloaded from. However, multicast sockets don't allow this sort of
restriction to be placed on the packets they send or receive. Once you send data to a
multicast socket, you have very limited and unreliable control over which hosts receive
that data. Consequently, most environments that execute remote code take the conserā
vative approach of disallowing all multicasting.
The Constructors
The constructors are simple. You can either pick a port to listen on or let Java assign an
anonymous port for you:
public
MulticastSocket
()
throws
SocketException
public
MulticastSocket
(
int
port
)
throws
SocketException
public
MulticastSocket
(
SocketAddress
bindAddress
)
throws
IOException
For example:
MulticastSocket
ms1
=
new
MulticastSocket
();
MulticastSocket
ms2
=
new
MulticastSocket
(
4000
);