Java Reference
In-Depth Information
Here's how it works:
Associate a socket channel with an input or output stream.
n
Configure the channel to recognize the kind of networking events you want to
monitor, such as new connections, attempts to read data over the channel, and
attempts to write data.
n
Call a method to open the channel.
n
Because the method is nonblocking, the program continues execution so that you
can handle other tasks.
n
If one of the networking events you are monitoring takes place, your program is
notified—a method associated with the event is called.
n
This is comparable to how user-interface components are programmed in Swing. An
interface component is associated with one or more event listeners and placed in a con-
tainer. If the interface component receives input being monitored by a listener, an event-
handling method is called. Until that happens, the program can handle other tasks.
17
To use nonblocking input and output, you must work with channels instead of streams.
Nonblocking Socket Clients and Servers
The first step in the development of a
nonblocking client or server is the creation of an object that represents the Internet
address to which you are making a connection. This task is handled by the
InetSocketAddress
class in the
java.net
package.
If the server is identified by a hostname, call
InetSocketAddress(
String
,
int
)
with
two arguments: the name of the server and its port number.
If the server is identified by its IP address, use the
InetAddress
class in
java.net
to
identify the host. Call the static method
InetAddress.getByName(
String)
with the IP
address of the host as the argument. The method returns an
InetAddress
object repre-
senting the address, which you can use in calling
InetSocketAddress(
InetAddress
,
int
)
. The second argument is the server's port number.
Nonblocking connections require a socket channel, another of the new classes in the
java.nio
package. Call the
open()
static method of the
SocketChannel
class to create
the channel.
A socket channel can be configured for blocking or nonblocking communication. To set
up a nonblocking channel, call the channel's
configureBlocking(
boolean
)
method with
an argument of
false
. Calling it with
true
makes it a blocking channel.