Example usage for java.nio.channels SelectionKey interestOps

List of usage examples for java.nio.channels SelectionKey interestOps

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey interestOps.

Prototype

public abstract SelectionKey interestOps(int ops);

Source Link

Document

Sets this key's interest set to the given value.

Usage

From source file:org.limewire.mojito.io.MessageDispatcherImpl.java

private void interest(int ops, boolean on) {
    try {//w w w .j a v  a 2 s .  c  o m
        SelectionKey sk = channel.keyFor(selector);
        if (sk != null && sk.isValid()) {
            synchronized (channel.blockingLock()) {
                if (on) {
                    sk.interestOps(sk.interestOps() | ops);
                } else {
                    sk.interestOps(sk.interestOps() & ~ops);
                }
            }
        }
    } catch (CancelledKeyException ignore) {
    }
}

From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java

private void send(ByteBuffer buffer) throws InterruptedException, IOException {
    if (!connected.get()) {
        throw new IOException("not connected");
    }/*w ww.  jav a  2 s .  co m*/
    synchronized (writeBuf) {
        // try direct write of what's in the buffer to free up space
        if (writeBuf.remaining() < buffer.remaining()) {
            writeBuf.flip();
            int bytesOp = 0, bytesTotal = 0;
            while (writeBuf.hasRemaining() && (bytesOp = channel.write(writeBuf)) > 0) {
                bytesTotal += bytesOp;
            }
            writeBuf.compact();
            logger.debug("Written {} bytes to the network", bytesTotal);
        }

        // if didn't help, wait till some space appears
        if (Thread.currentThread().getId() != thread.getId()) {
            while (writeBuf.remaining() < buffer.remaining()) {
                writeBuf.wait();
            }
        } else {
            if (writeBuf.remaining() < buffer.remaining()) {
                throw new IOException("send buffer full"); // TODO: add reallocation or buffers chain
            }
        }
        writeBuf.put(buffer);

        // try direct write to decrease the latency
        writeBuf.flip();
        int bytesOp = 0, bytesTotal = 0;
        while (writeBuf.hasRemaining() && (bytesOp = channel.write(writeBuf)) > 0) {
            bytesTotal += bytesOp;
        }
        writeBuf.compact();
        logger.debug("Written {} bytes to the network", bytesTotal);

        if (writeBuf.hasRemaining()) {
            SelectionKey key = channel.keyFor(selector);
            key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            selector.wakeup();
        }
    }
}

From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java

private void processConnect(SelectionKey key) throws Exception {
    SocketChannel ch = (SocketChannel) key.channel();
    if (ch.finishConnect()) {
        key.interestOps(key.interestOps() ^ SelectionKey.OP_CONNECT);
        key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        reconnectInterval = INITIAL_RECONNECT_INTERVAL;
        connected.set(true);/*  ww w. j  a  v  a  2 s . co m*/
        onConnected();
    }
}

From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java

private void processWrite(SelectionKey key) throws IOException {
    WritableByteChannel ch = (WritableByteChannel) key.channel();
    synchronized (writeBuf) {
        writeBuf.flip();//  w  w w  .  j a va2  s . com

        int bytesOp = 0, bytesTotal = 0;
        while (writeBuf.hasRemaining() && (bytesOp = ch.write(writeBuf)) > 0) {
            bytesTotal += bytesOp;
        }
        logger.debug("Written {} bytes to the network", bytesTotal);

        if (writeBuf.remaining() == 0) {
            key.interestOps(key.interestOps() ^ SelectionKey.OP_WRITE);
        }

        if (bytesTotal > 0) {
            writeBuf.notify();
        } else if (bytesOp == -1) {
            logger.info("peer closed write channel");
            ch.close();
        }

        writeBuf.compact();
    }
}

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Starts server in non-blocking mode./*  w  ww  . j  a v  a 2s. com*/
 * @since 1.4.5
 */
private void runNonBlocking(TheClient theClient) throws Exception {
    int selectCount = 0;
    Iterator iterator = null;
    SelectionKey key = null;
    ServerSocketChannel serverChannel = null;
    SocketChannel socketChannel = null;
    Socket client = null;
    ClientHandler _chPolled = null;
    boolean stopServerProcessed = false;
    int linger = getBasicConfig().getAdvancedSettings().getSocketLinger();
    registerChannelRequestMap = new HashMap();

    int socketTrafficClass = 0;
    if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
        socketTrafficClass = Integer
                .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass());
    }

    while (true) {
        selectCount = selector.select(500);
        //selectCount = selector.select();//for testing

        //check for any pending registerChannel req.
        synchronized (registerChannelRequestMap) {
            if (registerChannelRequestMap.size() > 0) {
                RegisterChannelRequest req = null;
                Object hashkey = null;
                iterator = registerChannelRequestMap.keySet().iterator();
                while (iterator.hasNext()) {
                    hashkey = iterator.next();
                    req = (RegisterChannelRequest) registerChannelRequestMap.get(hashkey);
                    req.register(getSelector());
                }
                iterator = null;
                registerChannelRequestMap.clear();
            } //if
        } //sync

        if (stopServer == true && stopServerProcessed == false) {
            logger.warning("Closing " + getName());
            serverSocketChannel.close();
            stopServerProcessed = true;

            server = null;
            serverSocketChannel = null;

            setServiceState(Service.STOPPED);
            logger.warning("Closed " + getName());

            processServerHooks(ServerHook.POST_SHUTDOWN);
        }

        if (stopServer == false && stopServerProcessed == true) {
            logger.finest("Server must have re-started.. will break");
            break;
        }

        if (selectCount == 0 && stopServerProcessed == true) {
            java.util.Set keyset = selector.keys();
            if (keyset.isEmpty() == true && getClientCount() <= 0) {
                break;
            } else {
                continue;
            }
        } else if (selectCount == 0) {
            continue;
        }

        iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            key = (SelectionKey) iterator.next();

            if (key.isValid() == false) {
                iterator.remove();
                continue;
            }

            if (key.isAcceptable() && stopServer == false) {
                logger.finest("Key is Acceptable");
                serverChannel = (ServerSocketChannel) key.channel();
                socketChannel = serverChannel.accept();

                if (socketChannel == null) {
                    iterator.remove();
                    continue;
                }

                client = socketChannel.socket();

                if (linger < 0) {
                    client.setSoLinger(false, 0);
                } else {
                    client.setSoLinger(true, linger);
                }

                client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay());

                if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
                    client.setTrafficClass(socketTrafficClass);//low delay=10
                }

                //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize());

                if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) {
                    client.setSendBufferSize(
                            getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize());
                    //logger.fine("SendBufferSize: "+client.getSendBufferSize());
                }

                if (checkAccessConstraint(client) == false) {
                    iterator.remove();
                    continue;
                }

                socketChannel.configureBlocking(false);
                theClient.setTrusted(getSkipValidation());
                theClient.setSocket(socketChannel.socket());
                theClient.setSocketChannel(socketChannel);

                if (clientDataClass != null) {
                    if (getClientDataPool() == null) {
                        clientData = (ClientData) clientDataClass.newInstance();
                    } else {
                        //borrow a object from pool
                        clientData = (ClientData) getClientDataPool().borrowObject();
                    }
                    theClient.setClientData(clientData);
                }

                //Check if max connection has reached
                if (getSkipValidation() != true && maxConnection != -1
                        && getClientHandlerPool().getNumActive() >= maxConnection) {
                    theClient.setClientEvent(ClientEvent.MAX_CON);
                } else {
                    theClient.setClientEvent(ClientEvent.ACCEPT);
                }

                try {
                    _chPolled = (ClientHandler) getClientHandlerPool().borrowObject();
                    logger.finest("Asking " + _chPolled.getName() + " to handle.");
                    _chPolled.handleClient(theClient);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.warning("Could not borrow ClientHandler Object from pool. Error: " + nsee);
                    logger.warning("Closing SocketChannel [" + serverChannel.socket()
                            + "] since no ClientHandler available.");
                    socketChannel.close();
                }

                if (_chPolled != null) {
                    try {
                        getClientPool().addClient(_chPolled, true);
                    } catch (java.util.NoSuchElementException nsee) {
                        logger.warning("Could not borrow Thread from pool. Error: " + nsee);
                        //logger.warning("Closing SocketChannel ["+serverChannel.socket()+"] since no Thread available.");
                        //socketChannel.close();
                        //returnClientHandlerToPool(_chPolled);
                    }
                    _chPolled = null;
                }
                socketChannel = null;
                client = null;

                setSkipValidation(false);//reset it back
            } else if (key.isValid() && key.isReadable()) {
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Readable, removing OP_READ from interestOps for " + _ch.getName());
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
                    _ch.addEvent(ClientEvent.READ);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.READ);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (key.isValid() && key.isWritable()) {
                if (getClientPool().shouldNioWriteHappen() == false) {
                    continue; //no need to remove the key
                }
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Writable, removing OP_WRITE from interestOps for " + _ch.getName());
                    //remove OP_WRITE from interest set
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
                    _ch.addEvent(ClientEvent.WRITE);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.WRITE);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (stopServer == true && key.isAcceptable()) {
                //we will not accept this key
                setSkipValidation(false);//reset it back
            } else {
                logger.warning("Unknown key got in SelectionKey: " + key);
            }
            iterator.remove(); //Remove key

            Thread.yield();
        } //end of iterator
        iterator = null;
    } //end of loop
}

From source file:voldemort.server.niosocket.AsyncRequestHandler.java

@Override
protected void write(SelectionKey selectionKey) throws IOException {
    if (outputStream.getBuffer().hasRemaining()) {
        // If we have data, write what we can now...
        try {//from w  w  w.  java 2 s . c o  m
            int count = socketChannel.write(outputStream.getBuffer());

            if (logger.isTraceEnabled())
                logger.trace("Wrote " + count + " bytes, remaining: " + outputStream.getBuffer().remaining()
                        + " for " + socketChannel.socket());
        } catch (IOException e) {
            if (streamRequestHandler != null) {
                streamRequestHandler.close(new DataOutputStream(outputStream));
                streamRequestHandler = null;
            }

            throw e;
        }

    } else {
        if (logger.isTraceEnabled())
            logger.trace("Wrote no bytes for " + socketChannel.socket());
    }

    // If there's more to write but we didn't write it, we'll take that to
    // mean that we're done here. We don't clear or reset anything. We leave
    // our buffer state where it is and try our luck next time.
    if (outputStream.getBuffer().hasRemaining())
        return;

    // If we don't have anything else to write, that means we're done with
    // the request! So clear the buffers (resizing if necessary).
    if (outputStream.getBuffer().capacity() >= resizeThreshold)
        outputStream.setBuffer(ByteBuffer.allocate(socketBufferSize));
    else
        outputStream.getBuffer().clear();

    if (streamRequestHandler != null && streamRequestHandler.getDirection() == StreamRequestDirection.WRITING) {
        // In the case of streaming writes, it's possible we can process
        // another segment of the stream. We process streaming writes this
        // way because there won't be any other notification for us to do
        // work as we won't be notified via reads.
        if (logger.isTraceEnabled())
            logger.trace("Request is streaming for " + socketChannel.socket());

        handleStreamRequest(selectionKey);
    } else {
        // If we're not streaming writes, signal the Selector that we're
        // ready to read the next request.
        selectionKey.interestOps(SelectionKey.OP_READ);
    }
}