Package java.nio.channels

Examples of java.nio.channels.SelectionKey


        SocketChannel channel = server.accept();
        if (channel==null) return;

        channel.configureBlocking(false);
        channel.socket().setTcpNoDelay(tcpNoDelay);
        SelectionKey readKey = channel.register(selector, SelectionKey.OP_READ);
        c = new Connection(readKey, channel, System.currentTimeMillis());
        readKey.attach(c);
        synchronized (connectionList) {
          connectionList.add(numConnections, c);
          numConnections++;
        }
        if (LOG.isDebugEnabled())
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(getName() + ": doAsyncWrite threw exception " + e);
            }
          }
          long now = System.currentTimeMillis();
          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.
          //
          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

            InetSocketAddress address = new InetSocketAddress(host, port);
            SocketChannel channel = SocketChannel.open();
   
            // configure the channel for no-blocking and selection
            channel.configureBlocking(false);
            SelectionKey selectionKey = channel.register(connectionManager.getNIODaemon().getSelector(), SelectionKey.OP_CONNECT);
   
            // prepare the handler for the connection
            client = CTPConnection.client(host, selectionKey, handler, connectionManager);
            selectionKey.attach(client);

            // connect (non-blocking)
            channel.connect(address);

        } catch(IOException e) {
View Full Code Here

     * @return the SelectionKey that is attached to the created connection.
     */
    public void handleAccept(SelectionKey key, Selector selector) {
        // construct the channels and selectors
        SocketChannel channel = null;
        SelectionKey channelKey = null;
        try {
            // peel the connection from the SocketChannel
            ServerSocketChannel server = (ServerSocketChannel)key.channel();
            channel = server.accept();

            // configure the channel for no-blocking and selection
            if(channel == null) return;
            channel.configureBlocking(false);
            channelKey = channel.register(selector, 0);
        } catch(IOException e) {
            // the accept failed, there's nothing to clean up
            return;
        }

        // construct handlers for this connection
        CTPHandler handler = handlerFactory.constructHandler();
        CTPConnection server = CTPConnection.server(channelKey, handler, this);
        channelKey.attach(server);
        server.handleConnect();
    }
View Full Code Here

     * Handles all keys which are ready to be processed.
     */
    void handle() {
        // Iterate over the selected keys
        for(Iterator i = nioDaemon.getSelector().selectedKeys().iterator(); i.hasNext(); ) {
            SelectionKey key = (SelectionKey)i.next();
            i.remove();
           
            // Is a new connection coming in?
            if(key.isValid() && key.isAcceptable()) {
                nioDaemon.getServer().handleAccept(key, nioDaemon.getSelector());
            }
           
            // an outgoing connection has been established
            if(key.isValid() && key.isConnectable()) {
                NIOAttachment attachment = (NIOAttachment)key.attachment();
                attachment.handleConnect();
            }

            // incoming data can be read
            if(key.isValid() && key.isReadable()) {
                NIOAttachment attachment = (NIOAttachment)key.attachment();
                attachment.handleRead();
            }
           
            // outgoing data can be written
            if(key.isValid() && key.isWritable()) {
                NIOAttachment attachment = (NIOAttachment)key.attachment();
                attachment.handleWrite();
            }

            // clean up broken connections
            if(!key.isValid()) {
                NIOAttachment attachment = (NIOAttachment)key.attachment();
                attachment.close(new IOException("Connection closed"));
            }
        }
    }
View Full Code Here

    public void run() {
        logger.info("Cleaning up listening socket and closing " + (nioDaemon.getSelector().keys().size()-1) + " connections");

        // kill all connections
        for(Iterator k = nioDaemon.getSelector().keys().iterator(); k.hasNext(); ) {
            SelectionKey key = (SelectionKey)k.next();

            // close an invalid connection
            if(!key.isValid()) {
                NIOAttachment attachment = (NIOAttachment)key.attachment();
                attachment.close(new IOException("Connection closed"));

            // close the server socket
            } else if((key.interestOps() & SelectionKey.OP_ACCEPT) != 0) {
                try {
                    ServerSocketChannel server = (ServerSocketChannel)key.channel();
                    server.close();
                    key.cancel();
                } catch(IOException e) {
                    logger.warning("Error closing server socket, " + e.getMessage());
                }
               
            // close a connection socket
            } else {
                NIOAttachment attachment = (NIOAttachment)key.attachment();
                attachment.close(new ServerShutdownException());
            }
        }
    }
View Full Code Here

        // Process any pending changes
        synchronized (this.pendingChanges)
        {
          for (NioChangeRequest change : this.pendingChanges)
          {
            SelectionKey key = change.socket.keyFor(this.selector);
            key.interestOps(change.ops);
          }
          this.pendingChanges.clear();
        }

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

        // Iterate over the set of keys for which events are available
        Set<SelectionKey> selectedkeys = this.selector.selectedKeys();
        for (SelectionKey key : selectedkeys)
        {
          selectedkeys.remove(key);

          // 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 (Exception e)
      {
View Full Code Here

        acceptSelector.select();

        // process the io events we received
        Iterator<SelectionKey> selectedKeys = acceptSelector.selectedKeys().iterator();
        while (!stopped_ && selectedKeys.hasNext()) {
          SelectionKey key = selectedKeys.next();
          selectedKeys.remove();

          // skip if not valid
          if (!key.isValid()) {
            continue;
          }

          if (key.isAcceptable()) {
            handleAccept();
          } else {
            LOGGER.warn("Unexpected state in select! " + key.interestOps());
          }
        }
      } catch (IOException e) {
        LOGGER.warn("Got an IOException while selecting!", e);
      }
View Full Code Here

        selector.select();

        // process the io events we received
        Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
        while (!stopped_ && selectedKeys.hasNext()) {
          SelectionKey key = selectedKeys.next();
          selectedKeys.remove();

          // skip if not valid
          if (!key.isValid()) {
            cleanupSelectionKey(key);
            continue;
          }

          if (key.isReadable()) {
            // deal with reads
            handleRead(key);
          } else if (key.isWritable()) {
            // deal with writes
            handleWrite(key);
          } else {
            LOGGER.warn("Unexpected state in select! " + key.interestOps());
          }
        }
      } catch (IOException e) {
        LOGGER.warn("Got an IOException while selecting!", e);
      }
View Full Code Here

        registerAccepted(accepted);
      }
    }

    private void registerAccepted(TNonblockingTransport accepted) {
      SelectionKey clientKey = null;
      try {
        clientKey = accepted.registerSelector(selector, SelectionKey.OP_READ);

        FrameBuffer frameBuffer = new FrameBuffer(accepted, clientKey, SelectorThread.this);
        clientKey.attach(frameBuffer);
      } catch (IOException e) {
        LOGGER.warn("Failed to register accepted connection to selector!", e);
        if (clientKey != null) {
          cleanupSelectionKey(clientKey);
        }
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.