Java Reference
In-Depth Information
SocketAddress
address
=
new
InetSocketAddress
(
"192.168.254.32"
,
4000
);
MulticastSocket
ms3
=
new
MulticastSocket
(
address
);
All three constructors throw a
SocketException
if the
Socket
can't be created. If you
don't have sufficient privileges to bind to the port or if the port you're trying to bind to
is already in use, then a
Socket
cannot be created. Note that because a multicast socket
is a datagram socket as far as the operating system is concerned, a
MulticastSocket
cannot occupy a port already occupied by a
DatagramSocket
, and vice versa.
You can pass null to the constructor to create an unbound socket, which will be con‐
nected later with the
bind()
method. This is useful when setting socket options that can
only be set before the socket is bound. For example, this code fragment creates a mul‐
ticast socket with SO_REUSEADDR disabled (that option is normally enabled by de‐
fault for multicast sockets):
MulticastSocket
ms
=
new
MulticastSocket
(
null
);
ms
.
setReuseAddress
(
false
);
SocketAddress
address
=
new
InetSocketAddress
(
4000
);
ms
.
bind
(
address
);
Communicating with a Multicast Group
Once a
MulticastSocket
has been created, it can perform four key operations:
1. Join a multicast group.
2. Send data to the members of the group.
3. Receive data from the group.
4. Leave the multicast group.
The
MulticastSocket
class has methods for operations 1 and 4. No new methods are
required to send or receive data. The
send()
and
receive()
methods of the superclass,
DatagramSocket
, suffice for those operations. You can perform these operations in any
order, with the exception that you must join a group before you can receive data from
it. You do not need to join a group to send data to it, and you can freely intermix sending
and receiving data.
Joining groups
To join a group, pass an
InetAddress
or a
SocketAddress
for the multicast group to
the
joinGroup()
method:
public
void
joinGroup
(
InetAddress
address
)
throws
IOException
public
void
joinGroup
(
SocketAddress
address
,
NetworkInterface
interface
)
throws
IOException