Package java.nio.channels

Examples of java.nio.channels.SelectionKey


     * @throws EOFException if read returns -1
     * @throws SocketTimeoutException if the read times out
     * @throws IOException if an IO Exception occurs in the underlying socket logic
     */
    public int read(ByteBuffer buf, NioChannel socket, long readTimeout) throws IOException {
        SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());
        if ( key == null ) throw new IOException("Key no longer registered");
        KeyAttachment att = (KeyAttachment) key.attachment();
        int read = 0;
        boolean timedout = false;
        int keycount = 1; //assume we can write
        long time = System.currentTimeMillis(); //start the timeout timer
        try {
View Full Code Here


                    if ( key == null ) return;
                    NioChannel nch = key.getChannel();
                    if ( nch == null ) return;
                    SocketChannel ch = nch.getIOChannel();
                    if ( ch == null ) return;
                    SelectionKey sk = ch.keyFor(selector);
                    try {
                        if (sk == null) {
                            sk = ch.register(selector, ops, key);
                        } else {
                            sk.interestOps(sk.interestOps() | ops);
                        }
                    }catch (CancelledKeyException cx) {
                        cancel(sk,key,ops);
                    }catch (ClosedChannelException cx) {
                        cancel(sk,key,ops);
View Full Code Here

                    if ( key == null ) return;
                    NioChannel nch = key.getChannel();
                    if ( nch == null ) return;
                    SocketChannel ch = nch.getIOChannel();
                    if ( ch == null ) return;
                    SelectionKey sk = ch.keyFor(selector);
                    try {
                        if (sk == null) {
                            if (SelectionKey.OP_WRITE==(ops&SelectionKey.OP_WRITE)) countDown(key.getWriteLatch());
                            if (SelectionKey.OP_READ==(ops&SelectionKey.OP_READ))countDown(key.getReadLatch());
                        } else {
                            sk.interestOps(sk.interestOps() & (~ops));
                            if (SelectionKey.OP_WRITE==(ops&SelectionKey.OP_WRITE)) countDown(key.getWriteLatch());
                            if (SelectionKey.OP_READ==(ops&SelectionKey.OP_READ))countDown(key.getReadLatch());
                            if (sk.interestOps()==0) {
                                sk.cancel();
                                sk.attach(null);
                            }
                        }
                    }catch (CancelledKeyException cx) {
                        if (sk!=null) {
                            sk.cancel();
                            sk.attach(null);
                        }
                    }
                }
            };
            events.offer(r);
View Full Code Here

                    Iterator iterator = keyCount > 0 ? selector.selectedKeys().iterator() : null;

                    // Walk through the collection of ready keys and dispatch
                    // any active event.
                    while (run && iterator != null && iterator.hasNext()) {
                        SelectionKey sk = (SelectionKey) iterator.next();
                        KeyAttachment attachment = (KeyAttachment)sk.attachment();
                        try {
                            attachment.access();
                            iterator.remove(); ;
                            sk.interestOps(sk.interestOps() & (~sk.readyOps()));
                            if ( sk.isReadable() ) {
                                countDown(attachment.getReadLatch());
                            }
                            if (sk.isWritable()) {
                                countDown(attachment.getWriteLatch());
                            }
                        }catch (CancelledKeyException ckx) {
                            if (sk!=null) sk.cancel();
                            countDown(attachment.getReadLatch());
                            countDown(attachment.getWriteLatch());
                        }
                    }//while
                }catch ( Throwable t ) {
View Full Code Here

            this.status = status;
        }
        
        public void run() {
            NioEndpoint.this.activeSocketProcessors.addAndGet(1);
            SelectionKey key = null;
            try {
                key = socket.getIOChannel().keyFor(socket.getPoller().getSelector());
                int handshake = -1;
               
                try {
                    if (key!=null) handshake = socket.handshake(key.isReadable(), key.isWritable());
                }catch ( IOException x ) {
                    handshake = -1;
                    if ( log.isDebugEnabled() ) log.debug("Error during SSL handshake",x);
                }catch ( CancelledKeyException ckx ) {
                    handshake = -1;
                }
                if ( handshake == 0 ) {
                    // Process the request from this socket
                    boolean closed = (status==null)?(handler.process(socket)==Handler.SocketState.CLOSED) :
                        (handler.event(socket,status)==Handler.SocketState.CLOSED);

                    if (closed) {
                        // Close socket and pool
                        try {
                            KeyAttachment ka = null;
                            if (key!=null) {
                                ka = (KeyAttachment) key.attachment();
                                if (ka!=null) ka.setComet(false);
                                socket.getPoller().cancelledKey(key, SocketStatus.ERROR, false);
                            }
                            if (socket!=null) nioChannels.offer(socket);
                            socket = null;
                            if ( ka!=null ) keyCache.offer(ka);
                            ka = null;
                        }catch ( Exception x ) {
                            log.error("",x);
                        }
                    }
                } else if (handshake == -1 ) {
                    KeyAttachment ka = null;
                    if (key!=null) {
                        ka = (KeyAttachment) key.attachment();
                        socket.getPoller().cancelledKey(key, SocketStatus.DISCONNECT, false);
                    }
                    if (socket!=null) nioChannels.offer(socket);
                    socket = null;
                    if ( ka!=null ) keyCache.offer(ka);
                    ka = null;
                } else {
                    final SelectionKey fk = key;
                    final int intops = handshake;
                    final KeyAttachment ka = (KeyAttachment)fk.attachment();
                    ka.getPoller().add(socket,intops);
                }
            }catch(CancelledKeyException cx) {
                socket.getPoller().cancelledKey(key,null,false);
            } catch (OutOfMemoryError oom) {
View Full Code Here

    }

    public Object getAttachment(boolean remove) {
        Poller pol = getPoller();
        Selector sel = pol!=null?pol.getSelector():null;
        SelectionKey key = sel!=null?getIOChannel().keyFor(sel):null;
        Object att = key!=null?key.attachment():null;
        if (key != null && att != null && remove ) key.attach(null);
        return att;
    }
View Full Code Here

        }
      }

      private synchronized void doRunLoop() {
        while (running) {
          SelectionKey key = null;
          try {
            // consume as many connections as currently queued to avoid
            // unbridled acceptance of connections that starves the select
            int size = pendingConnections.size();
            for (int i=size; i>0; i--) {
              Connection conn = pendingConnections.take();
              conn.channel.register(readSelector, SelectionKey.OP_READ, conn);
            }
            readSelector.select();

            Iterator<SelectionKey> iter = readSelector.selectedKeys().iterator();
            while (iter.hasNext()) {
              key = iter.next();
              iter.remove();
              if (key.isValid()) {
                if (key.isReadable()) {
                  doRead(key);
                }
              }
              key = null;
            }
View Full Code Here

        try {
          waitPending();     // If a channel is being registered, wait.
          writeSelector.select(PURGE_INTERVAL);
          Iterator<SelectionKey> iter = writeSelector.selectedKeys().iterator();
          while (iter.hasNext()) {
            SelectionKey key = iter.next();
            iter.remove();
            try {
              if (key.isValid() && key.isWritable()) {
                  doAsyncWrite(key);
              }
            } catch (IOException e) {
              LOG.info(Thread.currentThread().getName() + ": doAsyncWrite threw exception " + e);
            }
          }
          long now = Time.now();
          if (now < lastPurgeTime + PURGE_INTERVAL) {
            continue;
          }
          lastPurgeTime = now;
          //
          // If there were some calls that have not been sent out for a
          // long time, discard them.
          //
          if(LOG.isDebugEnabled()) {
            LOG.debug("Checking for old call responses.");
          }
          ArrayList<Call> calls;
         
          // get the list of channels from list of keys.
          synchronized (writeSelector.keys()) {
            calls = new ArrayList<Call>(writeSelector.keys().size());
            iter = writeSelector.keys().iterator();
            while (iter.hasNext()) {
              SelectionKey key = iter.next();
              Call call = (Call)key.attachment();
              if (call != null && key.channel() == call.connection.channel) {
                calls.add(call);
              }
            }
          }
         
View Full Code Here

    public void run() {
      LOG.info(Thread.currentThread().getName() + ": starting");
      SERVER.set(Server.this);
      connectionManager.startIdleScan();
      while (running) {
        SelectionKey key = null;
        try {
          getSelector().select();
          Iterator<SelectionKey> iter = getSelector().selectedKeys().iterator();
          while (iter.hasNext()) {
            key = iter.next();
            iter.remove();
            try {
              if (key.isValid()) {
                if (key.isAcceptable())
                  doAccept(key);
              }
            } catch (IOException e) {
            }
            key = null;
View Full Code Here

      logger.trace("Selecting keys");
      // For each key...
      while (i.hasNext()) {
        try {
          SelectionKey key = i.next();

          logger.trace("Selected new key.");
          if (key.isReadable()) {
            logger.trace("Reading from socket");
            readSocket(key);
          }
          if (key.isWritable()) {
            logger.trace("Writing data to socket");
            getContext(key, (SocketChannel) key.channel()).writeBufferToClient();
          }
          if (key.isAcceptable()) {
            SocketChannel client = acceptConnection();
            logger.trace("Accepted new connection from "+client.socket().getRemoteSocketAddress());
          }
          logger.trace("Selected key is processed.");
          i.remove(); // remove the key
View Full Code Here

TOP

Related Classes of java.nio.channels.SelectionKey

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.