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. 
     */ 
    protected 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. 
     */ 
    protected void handleWrite(SelectionKey key) {
      FrameBuffer buffer = (FrameBuffer) key.attachment();
      if (!buffer.write()) {
        cleanupSelectionKey(key);
      } 
    } 
 
    /** 
     * Do connection-close cleanup on a given SelectionKey. 
     */ 
    protected 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();
    } 
  } // SelectThread 
 
  /** 
   * Possible states for the FrameBuffer state machine.