Java Reference
In-Depth Information
SelectionKey key =
At this point, we don't know the type of event with which this SelectionKey is
associated. To fi nd this out, we need to retrieve the set of ready operations for the cur-
rent key by calling the SelectionKey method readyOps . This method returns the set of
operations as a bit pattern held in an int . By AND-ing this integer with specifi c
SelectionKey operation constants, we can determine whether those particular events
have been generated. For our program, of course, the only two event types of interest
are SelectionKey.OP_ACCEPT and SelectionKey.OP_READ . If the former is detected,
we shall process a new connection, whilst detection of the latter will lead to the pro-
cessing of incoming data. The code for determination of event type and the initiation
of processing (but not the details of such processing just yet) appears below.
int keyOps = key.readyOps();
if ((keyOps & SelectionKey.OP_ACCEPT) ==
acceptConnection(key); //Pass key to
//processing method.
continue; //Back to start of key-processing loop.
if ((keyOps & SelectionKey.OP_READ) ==
acceptData(key); //Pass key to processing method.
The processing required for a new connection has already been specifi ed in this
section, split across two separate locations in the text, but is now brought together
for the sake of clarity:
socketChannel = serverSocketChannel.accept();
socketChannel.confi gureBlocking(false);
socket = socketChannel.socket();
The only additional operation that is required is the removal of the current
SelectionKey from the selected set, in order to avoid re-processing it the next time
through the loop as though it represented a new event. This is effected by calling
method remove on the selected set, a reference to which may be obtained by calling
method selectedKeys again. The remove method will have the SelectionKey as its
single argument, of course:
Search WWH ::

Custom Search