Examples of SelectionKey


Examples of java.nio.channels.SelectionKey

        while((n = selector.select()) > 0) {
            // Someone is ready for I/O, get the ready keys
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            final Iterator<SelectionKey> keyItor = selectedKeys.iterator();
            while(keyItor.hasNext()) {
                SelectionKey key = keyItor.next();
                keyItor.remove();
                // The key indexes into the selector so you
                // can retrieve the socket that's ready for I/O
                Handler handler = (Handler) key.attachment();
                try {
                    handler.handle(key);
                } catch (CancelledKeyException cke) {
                    ;
                } catch (IOException ioe) {
View Full Code Here

Examples of java.nio.channels.SelectionKey

            throws IOException {
        int count = 1;
        int byteRead = 0;
        int preReadInputBBPos = byteBuffer.position();
        Selector readSelector = null;
        SelectionKey tmpKey = null;

        try {
            ReadableByteChannel readableChannel = (ReadableByteChannel) channel;
            while(count > 0) {
                count = readableChannel.read(byteBuffer);
                if(count > -1) {
                    byteRead += count;
                } else {
                    byteRead = count;
                }
            }

            if(byteRead == 0 && byteBuffer.position() == preReadInputBBPos) {
                readSelector = selectorFactory.getSelector();

                if(readSelector == null) {
                    return 0;
                }
                count = 1;

                tmpKey = channel.register(readSelector, SelectionKey.OP_READ);
                tmpKey.interestOps(tmpKey.interestOps() | SelectionKey.OP_READ);
                int code = readSelector.select(readTimeout);
                tmpKey.interestOps(tmpKey.interestOps() & (~SelectionKey.OP_READ));

                if(code == 0) {
                    return 0; // Return on the main Selector and try again.
                }

                while(count > 0) {
                    count = readableChannel.read(byteBuffer);
                    if(count > -1) {
                        byteRead += count;
                    } else {
                        byteRead = count;
                    }
                }
            } else if(byteRead == 0 && byteBuffer.position() != preReadInputBBPos) {
                byteRead += (byteBuffer.position() - preReadInputBBPos);
            }
        } finally {
            if(tmpKey != null) {
                tmpKey.cancel();
            }
            if(readSelector != null) {// Bug 6403933
                try {
                    readSelector.selectNow();
                } catch (IOException e) {
View Full Code Here

Examples of java.nio.channels.SelectionKey

      selector.selectNow();

    Set<SelectionKey> keys = selector.selectedKeys();
    synchronized (keys) {
      for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) {
        SelectionKey selectionKey = iter.next();
        iter.remove();
        try {
          int ops = selectionKey.readyOps();
          if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
            if (selectionKey.attachment() == tcp) {
              while (true) {
                Object object = tcp.readObject(this);
                if (object == null) break;
                if (!tcpRegistered) {
                  if (object instanceof RegisterTCP) {
View Full Code Here

Examples of java.nio.channels.SelectionKey

    synchronized (keys) {
      UdpConnection udp = this.udp;
      outer:
      //
      for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) {
        SelectionKey selectionKey = iter.next();
        iter.remove();
        try {
          int ops = selectionKey.readyOps();
          Connection fromConnection = (Connection)selectionKey.attachment();

          if (fromConnection != null) {
            // Must be a TCP read or write operation.
            if (udp != null && fromConnection.udpRemoteAddress == null) continue;
            if ((ops & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
View Full Code Here

Examples of java.nio.channels.SelectionKey

    connection.initialize(kryo, writeBufferSize, objectBufferSize);
    connection.endPoint = this;
    UdpConnection udp = this.udp;
    if (udp != null) connection.udp = udp;
    try {
      SelectionKey selectionKey = connection.tcp.accept(selector, socketChannel);
      selectionKey.attach(connection);

      int id = nextConnectionID++;
      if (nextConnectionID == -1) nextConnectionID = 1;
      connection.id = id;
      connection.setConnected(true);
View Full Code Here

Examples of java.nio.channels.SelectionKey


    /** We handle only non-SSL connections */
    void loop(Selector selector) {
        Set                 ready_keys;
        SelectionKey        key;
        ServerSocketChannel srv_sock;
        SocketChannel       in_sock, out_sock;
        InetSocketAddress   src, dest;

        while (true) {
            if (verbose)
                log("[Proxy] ready to accept connection");

            // 4. Call Selector.select()
            try {
                selector.select();

                // get set of ready objects
                ready_keys=selector.selectedKeys();
                for (Iterator it=ready_keys.iterator(); it.hasNext();) {
                    key=(SelectionKey) it.next();
                    it.remove();

                    if (key.isAcceptable()) {
                        srv_sock=(ServerSocketChannel) key.channel();
                        // get server socket and attachment
                        src=(InetSocketAddress) key.attachment();
                        in_sock=srv_sock.accept(); // accept request
                        if (verbose)
                            log("Proxy.loop()", "accepted connection from " + toString(in_sock));
                        dest=(InetSocketAddress) mappings.get(src);
                        // find corresponding dest
View Full Code Here

Examples of java.nio.channels.SelectionKey

        executor.execute(new Runnable() {
                public void run() {
                    Selector sel=null;
                    SocketChannel tmp;
                    Set ready_keys;
                    SelectionKey key;
                    ByteBuffer transfer_buf=ByteBuffer.allocate(BUFSIZE);

                    try {
                        sel=Selector.open();
                        in_channel.configureBlocking(false);
                        out_channel.configureBlocking(false);
                        in_channel.register(sel, SelectionKey.OP_READ);
                        out_channel.register(sel, SelectionKey.OP_READ);
                       
                        while (sel.select() > 0) {
                            ready_keys=sel.selectedKeys();
                            for (Iterator it=ready_keys.iterator(); it.hasNext();) {
                                key=(SelectionKey) it.next();
                                it.remove(); // remove current entry (why ?)
                                tmp=(SocketChannel) key.channel();
                                if (tmp == null) {
                                    log(
                                        "Proxy._handleConnection()",
                                        "attachment is null, continuing");
                                    continue;
                                }
                                if (key.isReadable()) { // data is available to be read from tmp
                                    if (tmp == in_channel) {
                                        // read all data from in_channel and forward it to out_channel (request)
                                        if (relay(tmp, out_channel, transfer_buf) == false)
                                            return;
                                    }
View Full Code Here

Examples of java.nio.channels.SelectionKey

    public static int readWithTemporarySelector(final SelectableChannel channel, final ByteBuffer byteBuffer, final long readTimeout, final NioSelectorPool selectorPool)
            throws IOException {
        final int preBufPos = byteBuffer.position();
        int byteRead = 0;
        Selector readSelector = null;
        SelectionKey tmpKey = null;

        try {
            ReadableByteChannel readableChannel = (ReadableByteChannel) channel;
            int count = 1;
            while(count > 0) {
                count = readableChannel.read(byteBuffer);
                if(count > -1) {
                    byteRead += count;
                } else {
                    byteRead = count;
                }
            }

            if(byteRead == 0 && byteBuffer.position() == preBufPos) {
                readSelector = selectorPool.getSelector();
                if(readSelector == null) {
                    return 0;
                }
                count = 1;

                tmpKey = channel.register(readSelector, SelectionKey.OP_READ);
                tmpKey.interestOps(tmpKey.interestOps() | SelectionKey.OP_READ);
                int code = readSelector.select(readTimeout);
                tmpKey.interestOps(tmpKey.interestOps() & (~SelectionKey.OP_READ));

                if(code == 0) {
                    return 0; // Return on the main Selector and try again.
                }

                while(count > 0) {
                    count = readableChannel.read(byteBuffer);
                    if(count > -1) {
                        byteRead += count;
                    } else {
                        byteRead = count;
                    }
                }
            } else if(byteRead == 0 && byteBuffer.position() != preBufPos) {
                byteRead += (byteBuffer.position() - preBufPos);
            }
        } finally {
            if(tmpKey != null) {
                tmpKey.cancel();
            }
            if(readSelector != null) {
                selectorPool.selectNowAndReturnSelector(readSelector);
            }
        }
View Full Code Here

Examples of java.nio.channels.SelectionKey

    private void nioLoop() throws IOException {
        this.selector.select(500);
        Set selectedKeys = this.selector.selectedKeys();
        Iterator i = selectedKeys.iterator();
        while (i.hasNext()) {
            SelectionKey key = (SelectionKey) i.next();
            if (key.isAcceptable()) {
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(this.selector, SelectionKey.OP_READ);
            } else if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer buffer = ByteBuffer.allocate(10);
                buffer.clear();
                sc.read(buffer);
                buffer.flip();
                sc.write(buffer);
View Full Code Here

Examples of java.nio.channels.SelectionKey

          while (changes.hasNext()) {
            ChangeRequest change = (ChangeRequest) changes.next();
            if (change.socket.isConnected()) {
              switch (change.type) {
                case ChangeRequest.CHANGEOPS:
                  SelectionKey key = change.socket.keyFor(this.selector);
                  if (key.isValid()) {
                    key.interestOps(change.ops);
                  }
              }
            }
          }
          this.pendingChanges.clear();
        }

        synchronized (this.pendingClosed) {
          Iterator<?> it = pendingClosed.iterator();
          while (it.hasNext()) {
            ChangeRequest change = (ChangeRequest) it.next();
            if (change.socket.isConnected()) {
              switch (change.type) {
                case ChangeRequest.CLOSE:
                  try {
                    /*
                     * Force data to be sent if there is data
                     * waiting.
                     */
                    if (pendingData.containsKey(change.socket)) {
                      SelectionKey key = change.socket.keyFor(selector);
                      if (key.isValid()) {
                        write(key);
                      }
                    }

                    /*
                     * Close the socket
                     */
                    change.socket.close();
                  } catch (Exception e) {
                    logger.info("Exception happened when closing socket", e);
                  }
                  break;
              }
            } else {
              logger.info("Closing a not connected socket");
            }
          }
          pendingClosed.clear();
        }

        // Wait for an event one of the registered channels
        this.selector.select();

        // Iterate over the set of keys for which events are available
        Iterator<?> selectedKeys = this.selector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
          SelectionKey key = (SelectionKey) selectedKeys.next();
          selectedKeys.remove();

          if (!key.isValid()) {
            continue;
          }

          // Check what event is available and deal with it
          if (key.isAcceptable()) {
            this.accept(key);
          } else if (key.isReadable()) {
            this.read(key);
          } else if (key.isWritable()) {
            this.write(key);
          }
        }
      } catch (IOException e) {
        logger.error("Error on NIOServer", e);
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.