Java Reference
In-Depth Information
tagramChannel
is opened and bound to
null
. The
null
value is important be-
cause by setting the
SocketAddress
equal to
null
, the socket will be bound to an
address that is assigned automatically. Next, a
ByteBuffer
is created that contains a
message that will be broadcast to any listeners. The message is then sent using the
Da-
tagramChannel
's
send(ByteBuffer, InetSocketAddress)
method. The
send()
method in the solution accepts the message as a
ByteBuffer
object, as
well as a new
InetSocketAddress
that is created by using the address and port,
which was declared at the beginning of the block. Told you we'd get back to those!
server.send(message, new InetSocketAddress(address,
port));
At this point, the client would receive the message that was sent by the server. As
for the client that is demonstrated in the solution to this recipe, it would then discon-
nect. Normally in a real-world scenario, a different class would most likely initiate the
server, and its
run()
method would contain a loop that would continue to execute un-
til all messages have been broadcast or the loop was told to stop. The client would
probably not disconnect until after a user initiated a shutdown.
21-5.
Generating
and
Reading
from
URLs
Problem
You want to generate URLs programmatically in your application. Once the URLs
have been created, you'd like to read data from them for use in your application.
Solution
Make use of the
java.net.URL
class in order to create an URL. There are a few dif-
ferent ways to generate an URL depending on the address you are attempting to work
with. This solution demonstrates a few different ways to create URL objects, along
with comments indicating the differences. Once the URL objects have been created,
one of the URLs is read into a
BufferedReader
and printed to the command line.