Java Reference
In-Depth Information
Continuebyenteringtextintheinputtextareathatappearsbelowtheusernametext-
field,andclicktheSendbuttontosendtheenteredtexttoallusers.Thistextappearsin
the output textarea that appears below the input textarea.
Finally, click the Quit button to terminate the chat.
DatagramSocket and MulticastSocket
The DatagramSocket and MulticastSocket classes let you perform UDP-
basedcommunicationsbetweenapairofhosts( DatagramSocket )orbetweenmul-
tiplehosts( MulticastSocket ).Witheitherclass,youcommunicateone-waymes-
sagesvia datagram packets ,whicharearraysofbytesassociatedwithinstancesofthe
DatagramPacket class.
Note Althoughyoumightthinkthat Socket and ServerSocket areallthatyou
need, DatagramSocket (and its MulticastSocket subclass) have their uses.
Forexample,considerascenariowhereagroupofmachinesneedtooccasionallytell
a server that they're alive. It shouldn't matter when the occasional message is lost or
evenwhenthemessagedoesn'tarriveontime.Anotherexampleisalow-prioritystock
tickerthatperiodicallybroadcastsstockprices.Whenapacketdoesn'tarrive,oddsare
thatthenextpacketwillarriveandyou'llthenreceivenotificationofthelatestprices.
Timely rather than reliable or orderly delivery is more important in realtime applica-
tions.
DatagramPacket declares several constructors with DatagramPack-
et(byte[] buf, int length) being the simplest. This constructor requires
youtopassbytearrayandintegerargumentsto buf and length ,where buf isadata
bufferthatstoresdatatobesentorreceived,and length (whichmustbelessthanor
equalto buf.length )specifiesthenumberofbytes(startingat buf[0] )tosendor
receive.
The following example demonstrates this constructor:
byte[] buffer = new byte[100];
DatagramPacket dgp = new DatagramPacket(buffer, buf-
fer.length);
Note Additional constructors let you specify an offset into buf that identifies the
storagelocationofthefirstoutgoingorincomingbyte,and/orletyouspecifyadestin-
ation socket address.
Search WWH ::




Custom Search