Java Reference
In-Depth Information
￿
SelectionKey.OP_ACCEPT
￿
SelectionKey.OP_CONNECT
￿
SelectionKey.OP_READ
￿
SelectionKey.OP_WRITE
These constants are int s with bit patterns that may be OR-ed together to form the
second argument for the register method. The two most commonly required con-
stants (and the ones that we shall be using) are SelectionKey.OP_ACCEPT and
SelectionKey.OP_READ . These will allow us to monitor new connections and data
transmissions from existing connections respectively. The fi rst will be of interest to
our ServerSocketChannel object, of course, while the second will be of interest to
our SocketChannel object.
The code for creating the Selector object and registering the respective interests
of our two channel objects is shown below. Note that, as with the ServerSocketChannel
object, a Selector object is created not via a constructor, but via static method open
that again creates an instance of a platform-specifi c sub-class that is hidden from the
programmer. Here and elsewhere in this section, the pre-declaration of a Selector
object called selector is assumed.
selector = Selector.open();
serverSocketChannel.register(selector,
SelectionKey.OP_ACCEPT);
.................................................
//The line below will occur rather later in the
//program, of course.
socketChannel.register(selector,
SelectionKey.OP_ READ);
The fi nal 'top level' step that needs to be carried out is the setting up of a Buffer
object (package java.nio ) to provide the shared data structure for the SocketChannel s
associated with connecting clients. Class Buffer itself is an abstract class, and so no
objects of this class can be created, but it has seven sub-classes from which objects
may be created:
￿
ByteBuffer
￿
CharBuffer
￿
IntBuffer
￿
LongBuffer
￿
ShortBuffer
￿
FloatBuffer
￿
DoubleBuffer
The last six of these are type-specifi c, but ByteBuffer supports reading and
writing of the other six types. This class is easily the most commonly used and is
the type that we shall be using. It has at its heart an array for storing the data and
we can specify the size of this array via method allocate , a static method of each
of the Buffer classes. The code below shows how this may be done. Of course, the
Search WWH ::




Custom Search