Java Reference
In-Depth Information
dgp.setLength(buffer.length);
mcs.send(dgp);
i++;
}
}
catch (IOException ioe)
{
System.err.println("i/o
error:
"+ioe.getMessage());
}
}
}
MulticastSocket()
constructor.Themulticastsocketdoesn'tneedtobindtoaport
numberbecausetheportnumberisspecifiedalongwiththemulticastgroup'sIPaddress
(231.0.0.1)aspartofthe
DatagramPacket
instancethat'ssubsequentlycreated.(The
dummy
array is present to prevent a
NullPointerException
object from being
thrownfromthe
DatagramPacket
constructor—thisarrayisn'tusedtostoredatato
be broadcasted.)
Atthispoint,
main()
entersaninfiniteloopthatfirstcreatesanarrayofbytesfrom
toconvertfromUnicodecharacterstobytes.(Althoughextraneous
StringBuilder
and
String
objectsarecreatedviaexpression
"line "+i
ineachloopiterationI'm
not worried about their impact on garbage collection in this short throwaway applica-
tion.)
Thisdatabufferissubsequentlyassignedtothe
DatagramPacket
instancebycall-
ing its
void setData(byte[] buf)
method, and then the datagram packet is
broadcasttoallmembersofthegroupassociatedwithport10000andmulticastIPad-
dress 231.0.0.1.
MCServer
). You shouldn't observe any output.
Listing 9-7
presents a multicasting client.
Listing 9-7.
Receiving multicasted datagram packets