Java Reference
In-Depth Information
}
}
port 10000 via the
MulticastSocket(int port)
constructor.
It then obtains an
InetAddress
object that contains multicast group IP address
231.0.0.1, and uses this object to join the group at this address by calling
Multic-
astSocket
's
void joinGroup(InetAddress mcastaddr)
method.
main()
next receives ten datagram packets, prints their contents, and leaves the
group by calling
MulticastSocket
's
void leaveGroup(InetAddress
mcastaddr)
method with the same multicast IP address as its argument.
Note
joinGroup()
and
leaveGroup()
throw
IOException
when an I/O
erroroccurswhileattemptingtojoinorleavethegroup,orwhentheIPaddressisnota
multicast IP address.
Because the client doesn't know exactly how long the arrays of bytes will be, it as-
sumes256bytestoensurethatthedatabufferwillholdtheentirearray.Ifittriedtoprint
outthereturnedarray,youwouldseealotofemptyspaceaftertheactualdatahadbeen
printed.Toeliminatethisspace,itinvokes
DatagramPacket
's
int getLength()
methodtoobtaintheactuallengthofthearray,createsasecondbytearray(
buffer2
)
thismanybytesto
buffer2
.Afterconvertingthisbytearraytoa
String
object(via
the
String(byte[] bytes)
constructor,whichusestheplatform'sdefaultcharac-
terset—see
Chapter8
tolearnaboutcharactersets),itprintstheresultingcharactersto
the standard output device.
MCClient
). You should observe output similar to the following:
line 521103
line 521104
line 521105
line 521106
line 521107
line 521108
line 521109
line 521110