Java Reference
In-Depth Information
At its basic level, sockets require a type, IP address, and port. While sockets literature
has consumed whole topics, the main idea is pretty straightforward. Like the post of-
fice, socket communication relies on addresses. These addresses are used to deliver
data. In this example, we picked the loopback (the same computer where the program
is running) address (127.0.0.1), and chose a random port number ( 2583 ).
The advantage of the new NIO.2 is that it is asynchronous in nature. By using asyn-
chronous calls, you can scale your application without creating thousands of threads for
each connection. In our example, we take the asynchronous calls and wait for a con-
nection, effectively making it single-threaded for the sake of the example, but don't let
that stop you for enhancing this example with more asynchronous calls. (Check the re-
cipes on the multithreaded section of this topic.)
For a client to connect, it requires a socket channel. The NIO.2 API allows creation
of asynchronous socket channels. Once a socket channel is created, it will need an ad-
dress to connect to. The socketChannel.connect() operation does not block;
instead it returns a Future object (this is a different from traditional NIO, where call-
ing socketChannel.connect() will block until a connection is established). The
Future object allows a Java program to continue what it is doing and simply query
the status of the submitted task. To take the analogy further, instead of waiting at the
front door for your mail to arrive, you go do other stuff, and “check” periodically to see
whether the mail has arrived. Future objects have methods like isDone() and
isCancelled() that let you know if the task is done or cancelled. It also has the
get() method, which allows you to actually wait for the task to finish. In our ex-
ample, we use the Future.get() to wait for the client connection to be established.
Once the connection is established, we use Channels.newOutputStream()
to create an output stream to send information. Using the decorator pattern, we decor-
ate the outputStream with our ObjectOutputStream to finally send objects
through the socket.
The server code is a little more elaborate. Server socket connections allow more
than one connection to occur, thus they are used to monitor or receive connections in-
stead of initiating a connection. For this reason, the server is usually waiting for a con-
nection asynchronously.
The server begins by establishing the address it listens to ( 127.0.0.1:2583 )
and accepting connections. The call to serverSocketChannel.accept() re-
turns another Future object that will give you the flexibility of how to deal with in-
coming connections. In our example, the server connection simply calls fu-
ture.get() , which will block (stop the execution of the program) until a connection
is accepted.
Search WWH ::




Custom Search