Java Reference
In-Depth Information
There's not a lot of call for this in a one-connection client like this one. Perhaps you
could check to see if the user has done something to cancel input, for example. However,
as you'll see in the next section, when a program is processing multiple connections,
this enables code to run very quickly on the fast connections and more slowly on the
slow ones. Each connection gets to run at its own speed without being held up behind
the slowest driver on the one-lane road.
An Example Server
Clients are well and good, but channels and buffers are really intended for server systems
that need to process many simultaneous connections efficiently. Handling servers re‐
quires a third new piece in addition to the buffers and channels used for the client.
Specifically, you need selectors that allow the server to find all the connections that are
ready to receive output or send input.
To demonstrate the basics, this example implements a simple server for the character
generator protocol. When implementing a server that takes advantage of the new I/O
APIs, begin by calling the static factory method ServerSocketChannel.open() method
to create a new ServerSocketChannel object:
ServerSocketChannel serverChannel = ServerSocketChannel . open ();
Initially, this channel is not actually listening on any port. To bind it to a port, retrieve
its ServerSocket peer object with the socket() method and then use the bind() meth‐
od on that peer. For example, this code fragment binds the channel to a server socket
on port 19:
ServerSocket ss = serverChannel . socket ();
ss . bind ( new InetSocketAddress ( 19 ));
In Java 7 and later, you can bind directly without retrieving the underlying
java.net.ServerSocket :
serverChannel.bind(new InetSocketAddress(19));
As with regular server sockets, binding to port 19 requires you to be root on Unix
(including Linux and Mac OS X). Nonroot users can only bind to ports 1024 and higher.
The server socket channel is now listening for incoming connections on port 19. To
accept one, call the accept() method, which returns a SocketChannel object:
SocketChannel clientChannel = serverChannel . accept ();
On the server side, you'll definitely want to make the client channel nonblocking to
allow the server to process multiple simultaneous connections:
clientChannel . configureBlocking ( false );
Search WWH ::




Custom Search