Java Code Examples for java.nio.channels.SelectionKey#OP_WRITE

The following examples show how to use java.nio.channels.SelectionKey#OP_WRITE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SocketFramework.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected void writeData( SelectionKey key ) throws IOException  {
    Queue<ByteBuffer> queue = getWriteQueue(key);
    int ops = SelectionKey.OP_READ;
    while( queue!= null ){
        ByteBuffer buffer = queue.peek();
        if ( buffer == null ){
            break;
        }
        else {
            int length = buffer.remaining();
            int written = ((SocketChannel)key.channel()).write(buffer);
            if (written < length) {
                // Not all bytes written. Socket's output buffer is full probably.
                // Keep the rest of this buffer in the write queue and wait until
                // the channel is writable again.
                ops |= SelectionKey.OP_WRITE;
                break;
            } else {
                // The whole content of the buffer written => remove it from the queue
                queue.poll();
            }
        }
    }
    key.interestOps(ops);
}
 
Example 2
Source File: TCPConnection.java    From gnirehtet with Apache License 2.0 6 votes vote down vote up
protected void updateInterests() {
    if (!selectionKey.isValid()) {
        return;
    }
    int interestOps = 0;
    if (mayRead()) {
        interestOps |= SelectionKey.OP_READ;
    }
    if (mayWrite()) {
        interestOps |= SelectionKey.OP_WRITE;
    }
    if (mayConnect()) {
        interestOps |= SelectionKey.OP_CONNECT;
    }
    if (interests != interestOps) {
        // interests must be changed
        interests = interestOps;
        selectionKey.interestOps(interestOps);
    }
}
 
Example 3
Source File: NioProcessor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void setInterestedInWrite(NioSession session, boolean isInterested) throws Exception {
    SelectionKey key = session.getSelectionKey();

    if (key == null) {
        return;
    }

    int newInterestOps = key.interestOps();

    if (isInterested) {
        newInterestOps |= SelectionKey.OP_WRITE;
        //newInterestOps &= ~SelectionKey.OP_READ;
    } else {
        newInterestOps &= ~SelectionKey.OP_WRITE;
        //newInterestOps |= SelectionKey.OP_READ;
    }

    key.interestOps(newInterestOps);
}
 
Example 4
Source File: AbstractNioByteChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
protected final void clearOpWrite() {
    final SelectionKey key = selectionKey();
    // Check first if the key is still valid as it may be canceled as part of the deregistration
    // from the EventLoop
    // See https://github.com/netty/netty/issues/2104
    if (!key.isValid()) {
        return;
    }
    final int interestOps = key.interestOps();
    if ((interestOps & SelectionKey.OP_WRITE) != 0) {
        key.interestOps(interestOps & ~SelectionKey.OP_WRITE);
    }
}
 
Example 5
Source File: DatagramChannelImpl.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Translates native poll revent set into a ready operation set
 */
public boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl ski) {
    int intOps = ski.nioInterestOps();
    int oldOps = ski.nioReadyOps();
    int newOps = initialOps;

    if ((ops & Net.POLLNVAL) != 0) {
        // This should only happen if this channel is pre-closed while a
        // selection operation is in progress
        // ## Throw an error if this channel has not been pre-closed
        return false;
    }

    if ((ops & (Net.POLLERR | Net.POLLHUP)) != 0) {
        newOps = intOps;
        ski.nioReadyOps(newOps);
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & Net.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0))
        newOps |= SelectionKey.OP_READ;

    if (((ops & Net.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0))
        newOps |= SelectionKey.OP_WRITE;

    ski.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 6
Source File: SelectChannelEndPoint.java    From WebSocket-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Updates selection key. Adds operations types to the selection key as needed. No operations
 * are removed as this is only done during dispatch. This method records the new key and
 * schedules a call to doUpdateKey to do the keyChange
 */
private void updateKey()
{
    final boolean changed;
    synchronized (this)
    {
        int current_ops=-1;
        if (getChannel().isOpen())
        {
            boolean read_interest = _readBlocked || (_state<STATE_DISPATCHED && !_connection.isSuspended());
            boolean write_interest= _writeBlocked || (_state<STATE_DISPATCHED && !_writable);

            _interestOps =
                ((!_socket.isInputShutdown() && read_interest ) ? SelectionKey.OP_READ  : 0)
            |   ((!_socket.isOutputShutdown()&& write_interest) ? SelectionKey.OP_WRITE : 0);
            try
            {
                current_ops = ((_key!=null && _key.isValid())?_key.interestOps():-1);
            }
            catch(Exception e)
            {
                _key=null;
                LOG.ignore(e);
            }
        }
        changed=_interestOps!=current_ops;
    }

    if(changed)
    {
        _selectSet.addChange(this);
        _selectSet.wakeup();
    }
}
 
Example 7
Source File: SctpMultiChannelImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Translates native poll revent ops into a ready operation ops
 */
private boolean translateReadyOps(int ops, int initialOps,
                                  SelectionKeyImpl sk) {
    int intOps = sk.nioInterestOps();
    int oldOps = sk.nioReadyOps();
    int newOps = initialOps;

    if ((ops & PollArrayWrapper.POLLNVAL) != 0) {
        /* This should only happen if this channel is pre-closed while a
         * selection operation is in progress
         * ## Throw an error if this channel has not been pre-closed */
        return false;
    }

    if ((ops & (PollArrayWrapper.POLLERR
                | PollArrayWrapper.POLLHUP)) != 0) {
        newOps = intOps;
        sk.nioReadyOps(newOps);
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & PollArrayWrapper.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0))
        newOps |= SelectionKey.OP_READ;

    if (((ops & PollArrayWrapper.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0))
        newOps |= SelectionKey.OP_WRITE;

    sk.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 8
Source File: SctpMultiChannelImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) {
    int newOps = 0;
    if ((ops & SelectionKey.OP_READ) != 0)
        newOps |= Net.POLLIN;
    if ((ops & SelectionKey.OP_WRITE) != 0)
        newOps |= Net.POLLOUT;
    sk.selector.putEventOps(sk, newOps);
}
 
Example 9
Source File: PullMetaDataConnection.java    From bt with Apache License 2.0 5 votes vote down vote up
@Override
public int calcInterestOps() {
	int ops = SelectionKey.OP_READ;
	if(isState(STATE_CONNECTING))
		ops |= SelectionKey.OP_CONNECT;
	if(!outputBuffers.isEmpty())
		ops |= SelectionKey.OP_WRITE;
				
	return ops;
}
 
Example 10
Source File: SctpMultiChannelImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) {
    int newOps = 0;
    if ((ops & SelectionKey.OP_READ) != 0)
        newOps |= Net.POLLIN;
    if ((ops & SelectionKey.OP_WRITE) != 0)
        newOps |= Net.POLLOUT;
    sk.selector.putEventOps(sk, newOps);
}
 
Example 11
Source File: TNonblockingSocket.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Writes to the underlying output stream if not null.
 */
public void write(byte[] buf, int off, int len) throws TTransportException {
  if ((socketChannel_.validOps() & SelectionKey.OP_WRITE) != SelectionKey.OP_WRITE) {
    throw new TTransportException(TTransportException.NOT_OPEN,
      "Cannot write to write-only socket channel");
  }
  try {
    socketChannel_.write(ByteBuffer.wrap(buf, off, len));
  } catch (IOException iox) {
    throw new TTransportException(TTransportException.UNKNOWN, iox);
  }
}
 
Example 12
Source File: SctpChannelImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Translates native poll revent ops into a ready operation ops
 */
private boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl sk) {
    int intOps = sk.nioInterestOps();
    int oldOps = sk.nioReadyOps();
    int newOps = initialOps;

    if ((ops & Net.POLLNVAL) != 0) {
        /* This should only happen if this channel is pre-closed while a
         * selection operation is in progress
         * ## Throw an error if this channel has not been pre-closed */
        return false;
    }

    if ((ops & (Net.POLLERR | Net.POLLHUP)) != 0) {
        newOps = intOps;
        sk.nioReadyOps(newOps);
        /* No need to poll again in checkConnect,
         * the error will be detected there */
        readyToConnect = true;
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & Net.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_READ;

    if (((ops & Net.POLLCONN) != 0) &&
        ((intOps & SelectionKey.OP_CONNECT) != 0) &&
        ((state == ChannelState.UNCONNECTED) || (state == ChannelState.PENDING))) {
        newOps |= SelectionKey.OP_CONNECT;
        readyToConnect = true;
    }

    if (((ops & Net.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_WRITE;

    sk.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 13
Source File: AbstractNioMessageChannel.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
protected void doWrite(ChannelOutboundBuffer in) throws Exception {
    final SelectionKey key = selectionKey();
    final int interestOps = key.interestOps();

    for (;;) {
        Object msg = in.current();
        if (msg == null) {
            // Wrote all messages.
            if ((interestOps & SelectionKey.OP_WRITE) != 0) {
                key.interestOps(interestOps & ~SelectionKey.OP_WRITE);
            }
            break;
        }
        try {
            boolean done = false;
            for (int i = config().getWriteSpinCount() - 1; i >= 0; i--) {
                if (doWriteMessage(msg, in)) {
                    done = true;
                    break;
                }
            }

            if (done) {
                in.remove();
            } else {
                // Did not write all messages.
                if ((interestOps & SelectionKey.OP_WRITE) == 0) {
                    key.interestOps(interestOps | SelectionKey.OP_WRITE);
                }
                break;
            }
        } catch (Exception e) {
            if (continueOnWriteError()) {
                in.remove(e);
            } else {
                throw e;
            }
        }
    }
}
 
Example 14
Source File: HTTPWriteHandler.java    From AdditionsAPI with MIT License 4 votes vote down vote up
@Override
public int getDefaultInterestSet()
{
	return SelectionKey.OP_WRITE;
}
 
Example 15
Source File: NioEndpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 *  所以我们能看到,线程池中线程大部分都在等待I/O操作。
 *  故此线程池应该被优化。Tomcat就在JDK基础上进行了优化。
 * 1.握手,建立对应链接。
 * 2.调用对应的连接器去处理此类请求。{@link Http11Processor#service(org.apache.tomcat.util.net.SocketWrapperBase)}
 */
@Override
protected void doRun() {
    NioChannel socket = socketWrapper.getSocket();
    SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());

    try {
        //握手?
        int handshake = -1;

        try {
            if (key != null) {
                if (socket.isHandshakeComplete()) {
                    // No TLS handshaking required. Let the handler
                    // process this socket / event combination.
                    handshake = 0;
                } else if (event == SocketEvent.STOP || event == SocketEvent.DISCONNECT ||
                        event == SocketEvent.ERROR) {
                    // Unable to complete the TLS handshake. Treat it as
                    // if the handshake failed.
                    handshake = -1;
                } else {
                    handshake = socket.handshake(key.isReadable(), key.isWritable());
                    // The handshake process reads/writes from/to the
                    // socket. status may therefore be OPEN_WRITE once
                    // the handshake completes. However, the handshake
                    // happens when the socket is opened so the status
                    // must always be OPEN_READ after it completes. It
                    // is OK to always set this as it is only used if
                    // the handshake completes.
                    event = SocketEvent.OPEN_READ;
                }
            }
        } catch (IOException x) {
            handshake = -1;
            if (log.isDebugEnabled()) log.debug("Error during SSL handshake",x);
        } catch (CancelledKeyException ckx) {
            handshake = -1;
        }

        /**
         * 握手成功?
         */
        if (handshake == 0) {
            SocketState state = SocketState.OPEN;
            // Process the request from this socket
            if (event == null) {
                /**
                 * 处理关键点 ConnectionHandler调用处理方法.
                 * {@link AbstractProtocol.ConnectionHandler#process(org.apache.tomcat.util.net.SocketWrapperBase, org.apache.tomcat.util.net.SocketEvent)}
                 */
                state = getHandler().process(socketWrapper, SocketEvent.OPEN_READ);
            } else {
                state = getHandler().process(socketWrapper, event);
            }
            if (state == SocketState.CLOSED) {
                close(socket, key);
            }
        } else if (handshake == -1 ) {
            getHandler().process(socketWrapper, SocketEvent.CONNECT_FAIL);
            close(socket, key);
        } else if (handshake == SelectionKey.OP_READ){
            socketWrapper.registerReadInterest();
        } else if (handshake == SelectionKey.OP_WRITE){
            socketWrapper.registerWriteInterest();
        }
    } catch (CancelledKeyException cx) {
        socket.getPoller().cancelledKey(key);
    } catch (VirtualMachineError vme) {
        ExceptionUtils.handleThrowable(vme);
    } catch (Throwable t) {
        log.error("", t);
        socket.getPoller().cancelledKey(key);
    } finally {
        socketWrapper = null;
        event = null;
        //return to cache
        if (running && !paused) {
            processorCache.push(this);
        }
    }
}
 
Example 16
Source File: SctpChannelImpl.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Translates native poll revent ops into a ready operation ops
 */
private boolean translateReadyOps(int ops, int initialOps, SelectionKeyImpl sk) {
    int intOps = sk.nioInterestOps();
    int oldOps = sk.nioReadyOps();
    int newOps = initialOps;

    if ((ops & Net.POLLNVAL) != 0) {
        /* This should only happen if this channel is pre-closed while a
         * selection operation is in progress
         * ## Throw an error if this channel has not been pre-closed */
        return false;
    }

    if ((ops & (Net.POLLERR | Net.POLLHUP)) != 0) {
        newOps = intOps;
        sk.nioReadyOps(newOps);
        /* No need to poll again in checkConnect,
         * the error will be detected there */
        readyToConnect = true;
        return (newOps & ~oldOps) != 0;
    }

    if (((ops & Net.POLLIN) != 0) &&
        ((intOps & SelectionKey.OP_READ) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_READ;

    if (((ops & Net.POLLCONN) != 0) &&
        ((intOps & SelectionKey.OP_CONNECT) != 0) &&
        ((state == ChannelState.UNCONNECTED) || (state == ChannelState.PENDING))) {
        newOps |= SelectionKey.OP_CONNECT;
        readyToConnect = true;
    }

    if (((ops & Net.POLLOUT) != 0) &&
        ((intOps & SelectionKey.OP_WRITE) != 0) &&
        isConnected())
        newOps |= SelectionKey.OP_WRITE;

    sk.nioReadyOps(newOps);
    return (newOps & ~oldOps) != 0;
}
 
Example 17
Source File: SelectChannelEndPoint.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
/** Called by selectSet to schedule handling
 *
 */
public void schedule()
{
    synchronized (this)
    {
        // If there is no key, then do nothing
        if (_key == null || !_key.isValid())
        {
            _readBlocked=false;
            _writeBlocked=false;
            this.notifyAll();
            return;
        }

        // If there are threads dispatched reading and writing
        if (_readBlocked || _writeBlocked)
        {
            // assert _dispatched;
            if (_readBlocked && _key.isReadable())
                _readBlocked=false;
            if (_writeBlocked && _key.isWritable())
                _writeBlocked=false;

            // wake them up is as good as a dispatched.
            this.notifyAll();

            // we are not interested in further selecting
            _key.interestOps(0);
            if (_state<STATE_DISPATCHED)
                updateKey();
            return;
        }

        // Remove writeable op
        if ((_key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE && (_key.interestOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE)
        {
            // Remove writeable op
            _interestOps = _key.interestOps() & ~SelectionKey.OP_WRITE;
            _key.interestOps(_interestOps);
            _writable = true; // Once writable is in ops, only removed with dispatch.
        }

        // If dispatched, then deregister interest
        if (_state>=STATE_DISPATCHED)
            _key.interestOps(0);
        else
        {
            // other wise do the dispatch
            dispatch();
            if (_state>=STATE_DISPATCHED && !_selectSet.getManager().isDeferringInterestedOps0())
            {
                _key.interestOps(0);
            }
        }
    }
}
 
Example 18
Source File: SctpChannel.java    From dragonwell8_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns an operation set identifying this channel's supported operations.
 *
 * <P> SCTP channels support connecting, reading, and writing, so this
 * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
 * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link
 * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
 *
 * @return  The valid-operation set
 */
@Override
public final int validOps() {
    return (SelectionKey.OP_READ |
            SelectionKey.OP_WRITE |
            SelectionKey.OP_CONNECT);
}
 
Example 19
Source File: SctpChannel.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns an operation set identifying this channel's supported operations.
 *
 * <P> SCTP channels support connecting, reading, and writing, so this
 * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
 * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link
 * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
 *
 * @return  The valid-operation set
 */
@Override
public final int validOps() {
    return (SelectionKey.OP_READ |
            SelectionKey.OP_WRITE |
            SelectionKey.OP_CONNECT);
}
 
Example 20
Source File: SctpChannel.java    From jdk8u_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns an operation set identifying this channel's supported operations.
 *
 * <P> SCTP channels support connecting, reading, and writing, so this
 * method returns <tt>(</tt>{@link SelectionKey#OP_CONNECT}
 * <tt>|</tt>&nbsp;{@link SelectionKey#OP_READ} <tt>|</tt>&nbsp;{@link
 * SelectionKey#OP_WRITE}<tt>)</tt>.  </p>
 *
 * @return  The valid-operation set
 */
@Override
public final int validOps() {
    return (SelectionKey.OP_READ |
            SelectionKey.OP_WRITE |
            SelectionKey.OP_CONNECT);
}