Code example for SelectionKey

Methods: attachment, cancel

0
    /** 
     * Do the work required to read from a readable client. If the frame is 
     * fully read, then invoke the method call. 
     */ 
    private void handleRead(SelectionKey key) {
      FrameBuffer buffer = (FrameBuffer)key.attachment();
      if (!buffer.read()) {
        cleanupSelectionkey(key);
        return; 
      } 
 
      // if the buffer's frame read is complete, invoke the method. 
      if (buffer.isFrameFullyRead()) {
        if (!requestInvoke(buffer)) {
          cleanupSelectionkey(key);
        } 
      } 
    } 
 
    /** 
     * Let a writable client get written, if there's data to be written. 
     */ 
    private void handleWrite(SelectionKey key) {
      FrameBuffer buffer = (FrameBuffer)key.attachment();
      if (!buffer.write()) {
        cleanupSelectionkey(key);
      } 
    } 
 
    /** 
     * Do connection-close cleanup on a given SelectionKey. 
     */ 
    private void cleanupSelectionkey(SelectionKey key) {
      // remove the records from the two maps 
      FrameBuffer buffer = (FrameBuffer)key.attachment();
      if (buffer != null) {
        // close the buffer 
        buffer.close();
      } 
      // cancel the selection key 
      key.cancel();
    } 
  } // SelectorThread 
 
  /** 
   * Class that implements a sort of state machine around the interaction with