Java Reference
In-Depth Information
Leaving groups and closing the connection
Call the
leaveGroup()
method when you no longer want to receive datagrams from the
specified multicast group, on either all or a specified network interface:
public
void
leaveGroup
(
InetAddress
address
)
throws
IOException
public
void
leaveGroup
(
SocketAddress
multicastAddress
,
NetworkInterface
interface
)
throws
IOException
It signals the local multicast router, telling it to stop sending you datagrams. If the
address you try to leave is not a multicast address (if it is not between 224.0.0.0 and
239.255.255.255), the method throws an
IOException
. However, no exception occurs
if you leave a multicast group you never joined.
Pretty much all the methods in
MulticastSocket
can throw an
IOException
, so you'll
usually wrap all this in a
try
block. In Java 7,
DatagramSocket
implements
Autocloseable
so you can use try-with-resources:
try
(
MulticastSocket
socket
=
new
MulticastSocket
())
{
// connect to the server...
}
catch
(
IOException
ex
)
{
ex
.
printStackTrace
();
}
In Java 6 and earlier, you'll want to explicitly close the socket in a
finally
block to
release resources the socket holds:
MulticastSocket
socket
=
null
;
try
{
socket
=
new
MulticastSocket
();
// connect to the server...
}
catch
(
IOException
ex
)
{
ex
.
printStackTrace
();
}
finally
{
if
(
socket
!=
null
)
{
try
{
socket
.
close
();
}
catch
(
IOException
ex
)
{
// ignore
}
}
}
Sending multicast data
Sending data with a
MulticastSocket
is similar to sending data with a
DatagramSock
et
. Stuff your data into a
DatagramPacket
object and send it off using the
send()
method
inherited from
DatagramSocket
. The data is sent to every host that belongs to the mul‐
ticast group to which the packet is addressed. For example: