Java Reference
In-Depth Information
After the channel is configured, call its
connect(
InetSocketAddress
)
method to con-
nect the socket.
On a blocking channel, the
connect()
method attempts to establish a connection to the
server and waits until it is complete, returning a value of
true
to indicate success.
On a nonblocking channel, the
connect()
method returns immediately with a value of
false
. To figure out what's going on over the channel and respond to events, you must
use a channel-listening object called a
Selector
.
A
Selector
is an object that keeps track of things that happen to a socket channel (or
another channel in the package that is a subclass of
SelectableChannel
).
To create a
Selector
, call its
open()
method, as in the following statement:
Selector monitor = Selector.open();
When you use a
Selector
, you must indicate the events you are interested in monitoring.
This is handled by calling a channel's
register(
Selector
,
int
,
Object
)
method.
The three arguments to
register()
are the following:
The
Selector
object you have created to monitor the channel
n
An
int
value that represents the events being monitored (also called selection
keys)
n
An
Object
that can be delivered along with the key, or
null
otherwise
n
Instead of using an integer value as the second argument, it's easier to use one or more
class variables from the
SelectionKey
class:
SelectionKey.OP_CONNECT
to monitor con-
nections,
SelectionKey.OP_READ
to monitor attempts to read data, and
SelectionKey.OP_WRITE
to monitor attempts to write data.
The following statements create a
Selector
to monitor a socket channel called
wire
for
reading data:
Selector spy = Selector.open();
channel.register(spy, SelectionKey.OP_READ, null);
To monitor more than one kind of key, add the
SelectionKey
class variables together.
For example:
Selector spy = Selector.open();
channel.register(spy, SelectionKey.OP_READ + SelectionKey.OP_WRITE, null);