Code example for SelectionKey

Methods: interestOpsisConnectableisReadableisValidisWritablereadyOps

0
     * @param key SelectionKey 
     * @return boolean 
     * @throws IOException 
     */ 
    public boolean process(SelectionKey key, boolean waitForAck) throws IOException {
        int ops = key.readyOps();
        key.interestOps(key.interestOps() & ~ops);
        //in case disconnect has been called 
        if ((!isConnected()) && (!connecting)) throw new IOException("Sender has been disconnected, can't selection key.");
        if ( !key.isValid() ) throw new IOException("Key is not valid, it must have been cancelled.");
        if ( key.isConnectable() ) {
            if ( socketChannel.finishConnect() ) {
                completeConnect(); 
                if ( current != null ) key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
                return false; 
            } else  { 
                //wait for the connection to finish 
                key.interestOps(key.interestOps() | SelectionKey.OP_CONNECT);
                return false; 
            }//end if 
        } else if ( key.isWritable() ) {
            boolean writecomplete = write(key);
            if ( writecomplete ) {
                //we are completed, should we read an ack? 
                if ( waitForAck ) {
                    //register to read the ack 
                    key.interestOps(key.interestOps() | SelectionKey.OP_READ);
                } else { 
                    //if not, we are ready, setMessage will reregister us for another write interest 
                    //do a health check, we have no way of verify a disconnected 
                    //socket since we don't register for OP_READ on waitForAck=false 
                    read(key);//this causes overhead
                    setRequestCount(getRequestCount()+1); 
                    return true; 
                } 
            } else { 
                //we are not complete, lets write some more 
                key.interestOps(key.interestOps()|SelectionKey.OP_WRITE);
            }//end if 
        } else if ( key.isReadable() ) {
            boolean readcomplete = read(key);
            if ( readcomplete ) {
                setRequestCount(getRequestCount()+1); 
                return true; 
            } else { 
                key.interestOps(key.interestOps() | SelectionKey.OP_READ);
            }//end if 
        } else { 
            //unknown state, should never happen 
            log.warn("Data is in unknown state. readyOps="+ops);
            throw new IOException("Data is in unknown state. readyOps="+ops);
Contextual code suggestions in your IDE  Get Codota for Java