Search in sources :

Example 81 with SelectionKey

use of java.nio.channels.SelectionKey in project cobar by alibaba.

the class AbstractConnection method enableWrite.

/**
     * 打开写事件
     */
private void enableWrite() {
    final Lock lock = this.keyLock;
    lock.lock();
    try {
        SelectionKey key = this.processKey;
        key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
    } finally {
        lock.unlock();
    }
    processKey.selector().wakeup();
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock)

Example 82 with SelectionKey

use of java.nio.channels.SelectionKey in project cobar by alibaba.

the class AbstractConnection method disableRead.

/**
     * 关闭读事件
     */
public void disableRead() {
    final Lock lock = this.keyLock;
    lock.lock();
    try {
        SelectionKey key = this.processKey;
        key.interestOps(key.interestOps() & OP_NOT_READ);
    } finally {
        lock.unlock();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock)

Example 83 with SelectionKey

use of java.nio.channels.SelectionKey in project voldemort by voldemort.

the class AbstractSelectorManager method close.

public void close() {
    // the punch...
    if (!isClosed.compareAndSet(false, true))
        return;
    try {
        for (SelectionKey sk : selector.keys()) {
            try {
                if (logger.isTraceEnabled())
                    logger.trace("Closing SelectionKey's channel");
                sk.channel().close();
                Object attachment = sk.attachment();
                if (attachment instanceof Closeable) {
                    IOUtils.closeQuietly((Closeable) attachment);
                }
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.WARN))
                    logger.warn(e.getMessage(), e);
            }
            try {
                if (logger.isTraceEnabled())
                    logger.trace("Cancelling SelectionKey");
                sk.cancel();
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.WARN))
                    logger.warn(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.WARN))
            logger.warn(e.getMessage(), e);
    }
    try {
        selector.close();
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.WARN))
            logger.warn(e.getMessage(), e);
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) Closeable(java.io.Closeable) VoldemortException(voldemort.VoldemortException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) IOException(java.io.IOException)

Example 84 with SelectionKey

use of java.nio.channels.SelectionKey in project voldemort by voldemort.

the class ClientRequestExecutor method addClientRequest.

public synchronized void addClientRequest(ClientRequest<?> clientRequest, long timeoutMs, long elapsedNs) {
    if (logger.isTraceEnabled()) {
        logger.trace("Associating client with " + socketChannel.socket());
    }
    this.clientRequest = clientRequest;
    computeExpirationTime(timeoutMs, elapsedNs);
    outputStream.getBuffer().clear();
    boolean wasSuccessful = clientRequest.formatRequest(outputStream);
    outputStream.getBuffer().flip();
    if (wasSuccessful) {
        SelectionKey selectionKey = socketChannel.keyFor(selector);
        if (selectionKey != null) {
            selectionKey.interestOps(SelectionKey.OP_WRITE);
            // This wakeup is required because it's invoked by the calling
            // code in a different thread than the SelectorManager.
            selector.wakeup();
        } else {
            /*
                 * Servers could close the Socket during bounce or other
                 * situations. In those cases the cached client connections are
                 * cleared up as well. But there is a race condition between the
                 * requests getting cached connections and connections getting
                 * cleared up. In those cases a request could get a connection
                 * but before sending request, it could have been invalidated
                 * and removed from the selector. This place handles the case by
                 * sending an IO Error to the request.
                 * 
                 * This case is no different than the request sent to the server
                 * and the server closing the socket.
                 */
            String message = "Client associated with " + socketChannel.socket() + " was not registered with Selector " + selector + ", it could have been closed due to server restarts ";
            logger.warn(message);
            IOException ex = new IOException(message);
            reportException(ex);
            completeClientRequest();
        }
    } else {
        logger.warn("Client associated with " + socketChannel.socket() + " did not successfully buffer output for request");
        completeClientRequest();
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) IOException(java.io.IOException)

Example 85 with SelectionKey

use of java.nio.channels.SelectionKey in project quorrabot by GloriousEggroll.

the class WebSocketServer method run.

// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
    synchronized (this) {
        if (selectorthread != null) {
            throw new IllegalStateException(getClass().getName() + " can only be started once.");
        }
        selectorthread = Thread.currentThread();
        if (isclosed.get()) {
            return;
        }
    }
    selectorthread.setName("WebsocketSelector" + selectorthread.getId());
    try {
        server = ServerSocketChannel.open();
        server.configureBlocking(false);
        ServerSocket socket = server.socket();
        socket.setReceiveBufferSize(WebSocketImpl.RCVBUF);
        socket.bind(address);
        selector = Selector.open();
        server.register(selector, server.validOps());
    } catch (IOException ex) {
        handleFatal(null, ex);
        return;
    }
    try {
        while (!selectorthread.isInterrupted()) {
            SelectionKey key = null;
            WebSocketImpl conn = null;
            try {
                selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> i = keys.iterator();
                while (i.hasNext()) {
                    key = i.next();
                    if (!key.isValid()) {
                        // Object o = key.attachment();
                        continue;
                    }
                    if (key.isAcceptable()) {
                        if (!onConnect(key)) {
                            key.cancel();
                            continue;
                        }
                        SocketChannel channel = server.accept();
                        channel.configureBlocking(false);
                        WebSocketImpl w = wsf.createWebSocket(this, drafts, channel.socket());
                        w.key = channel.register(selector, SelectionKey.OP_READ, w);
                        w.channel = wsf.wrapChannel(channel, w.key);
                        i.remove();
                        allocateBuffers(w);
                        continue;
                    }
                    if (key.isReadable()) {
                        conn = (WebSocketImpl) key.attachment();
                        ByteBuffer buf = takeBuffer();
                        try {
                            if (SocketChannelIOHelper.read(buf, conn, conn.channel)) {
                                if (buf.hasRemaining()) {
                                    conn.inQueue.put(buf);
                                    queue(conn);
                                    i.remove();
                                    if (conn.channel instanceof WrappedByteChannel) {
                                        if (((WrappedByteChannel) conn.channel).isNeedRead()) {
                                            iqueue.add(conn);
                                        }
                                    }
                                } else {
                                    pushBuffer(buf);
                                }
                            } else {
                                pushBuffer(buf);
                            }
                        } catch (IOException e) {
                            pushBuffer(buf);
                            throw e;
                        }
                    }
                    if (key.isWritable()) {
                        conn = (WebSocketImpl) key.attachment();
                        if (SocketChannelIOHelper.batch(conn, conn.channel)) {
                            if (key.isValid()) {
                                key.interestOps(SelectionKey.OP_READ);
                            }
                        }
                    }
                }
                while (!iqueue.isEmpty()) {
                    conn = iqueue.remove(0);
                    WrappedByteChannel c = ((WrappedByteChannel) conn.channel);
                    ByteBuffer buf = takeBuffer();
                    try {
                        if (SocketChannelIOHelper.readMore(buf, conn, c)) {
                            iqueue.add(conn);
                        }
                        if (buf.hasRemaining()) {
                            conn.inQueue.put(buf);
                            queue(conn);
                        } else {
                            pushBuffer(buf);
                        }
                    } catch (IOException e) {
                        pushBuffer(buf);
                        throw e;
                    }
                }
            } catch (CancelledKeyException e) {
            // an other thread may cancel the key
            } catch (ClosedByInterruptException e) {
                // do the same stuff as when InterruptedException is thrown
                return;
            } catch (IOException ex) {
                if (key != null) {
                    key.cancel();
                }
                handleIOException(key, conn, ex);
            } catch (InterruptedException e) {
                // FIXME controlled shutdown (e.g. take care of buffermanagement)
                return;
            }
        }
    } catch (RuntimeException e) {
        // should hopefully never occur
        handleFatal(null, e);
    } finally {
        if (decoders != null) {
            for (WebSocketWorker w : decoders) {
                w.interrupt();
            }
        }
        if (server != null) {
            try {
                server.close();
            } catch (IOException e) {
                onError(null, e);
            }
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) CancelledKeyException(java.nio.channels.CancelledKeyException) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) WrappedByteChannel(org.java_websocket.WrappedByteChannel) WebSocketImpl(org.java_websocket.WebSocketImpl)

Aggregations

SelectionKey (java.nio.channels.SelectionKey)202 IOException (java.io.IOException)93 SocketChannel (java.nio.channels.SocketChannel)59 Selector (java.nio.channels.Selector)44 ServerSocketChannel (java.nio.channels.ServerSocketChannel)41 ClosedChannelException (java.nio.channels.ClosedChannelException)30 InetSocketAddress (java.net.InetSocketAddress)27 CancelledKeyException (java.nio.channels.CancelledKeyException)25 ByteBuffer (java.nio.ByteBuffer)24 ClosedSelectorException (java.nio.channels.ClosedSelectorException)17 SelectableChannel (java.nio.channels.SelectableChannel)13 Test (org.junit.Test)13 Iterator (java.util.Iterator)9 Socket (java.net.Socket)7 ArrayList (java.util.ArrayList)7 SocketTimeoutException (java.net.SocketTimeoutException)6 AbstractSelectionKey (java.nio.channels.spi.AbstractSelectionKey)6 EOFException (java.io.EOFException)5 DatagramChannel (java.nio.channels.DatagramChannel)5 HashSet (java.util.HashSet)5