Java Reference
In-Depth Information
dgp.setLength(buffer.length);
mcs.send(dgp);
i++;
}
}
catch (IOException ioe)
{
System.err.println("i/o
error:
"+ioe.getMessage());
}
}
}
Listing 9-6 ' s main() method first creates a MulticastSocket instance via the
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
a String instance,andusestheplatform'sdefaultcharacterencoding(see Chapter8 )
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.
Compile Listing 9-6 ( javac MCServer.java ) and run this application ( java
MCServer ). You shouldn't observe any output.
Listing 9-7 presents a multicasting client.
Listing 9-7. Receiving multicasted datagram packets
Search WWH ::




Custom Search