Java Code Examples for java.nio.channels.SelectionKey#isValid()

The following examples show how to use java.nio.channels.SelectionKey#isValid() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SelectorImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void registerInterestOps(EventHandler eventHandler)
{
    if (orb.transportDebugFlag) {
        dprint(".registerInterestOps:-> " + eventHandler);
    }

    SelectionKey selectionKey = eventHandler.getSelectionKey();
    if (selectionKey.isValid()) {
        int ehOps = eventHandler.getInterestOps();
        SelectionKeyAndOp keyAndOp = new SelectionKeyAndOp(selectionKey, ehOps);
        synchronized(interestOpsList) {
            interestOpsList.add(keyAndOp);
        }
        // tell Selector Thread there's an update to a SelectorKey's Ops
        try {
            if (selector != null) {
                // wakeup Selector thread to process close request
                selector.wakeup();
            }
        } catch (Throwable t) {
            if (orb.transportDebugFlag) {
                dprint(".registerInterestOps: selector.wakeup: ", t);
            }
        }
    }
    else {
        wrapper.selectionKeyInvalid(eventHandler.toString());
        if (orb.transportDebugFlag) {
            dprint(".registerInterestOps: EventHandler SelectionKey not valid " + eventHandler);
        }
    }

    if (orb.transportDebugFlag) {
        dprint(".registerInterestOps:<- ");
    }
}
 
Example 2
Source File: DataReceivingLoop.java    From bt with Apache License 2.0 5 votes vote down vote up
/**
 * @return true, if the key has been processed and can be removed
 */
private boolean processKey(final SelectionKey key) {
    ChannelHandlerContext handler = getHandlerContext(key);
    if (!key.isValid() || !key.isReadable()) {
        return true;
    }
    return handler.readFromChannel();
}
 
Example 3
Source File: ConnectionHandler.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
public static void handleKey(SelectionKey key) {
    ConnectionHandler handler = ((ConnectionHandler)key.attachment());
    try {
        if (handler == null)
            return;
        if (!key.isValid()) {
            handler.closeConnection(); // Key has been cancelled, make sure the socket gets closed
            return;
        }
        if (key.isReadable()) {
            // Do a socket read and invoke the connection's receiveBytes message
            int read = handler.channel.read(handler.readBuff);
            if (read == 0)
                return; // Was probably waiting on a write
            else if (read == -1) { // Socket was closed
                key.cancel();
                handler.closeConnection();
                return;
            }
            // "flip" the buffer - setting the limit to the current position and setting position to 0
            handler.readBuff.flip();
            // Use connection.receiveBytes's return value as a check that it stopped reading at the right location
            int bytesConsumed = checkNotNull(handler.connection).receiveBytes(handler.readBuff);
            checkState(handler.readBuff.position() == bytesConsumed);
            // Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative
            // position)
            handler.readBuff.compact();
        }
        if (key.isWritable())
            handler.tryWriteBytes();
    } catch (Exception e) {
        // This can happen eg if the channel closes while the thread is about to get killed
        // (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
        Throwable t = Throwables.getRootCause(e);
        log.warn("Error handling SelectionKey: {} {}", t.getClass().getName(), t.getMessage() != null ? t.getMessage() : "", e);
        handler.closeConnection();
    }
}
 
Example 4
Source File: TThreadedSelectorServerWithFix.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
/**
 * Select and process IO events appropriately: If there are connections to
 * be accepted, accept them.
 */
private void select() {
  try {
    // wait for connect events.
    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);
  }
}
 
Example 5
Source File: NioSocketConnector.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void processTimedOutSessions() {
	long currentTime = System.currentTimeMillis();
	for (SelectionKey key : selector.keys()) {
		ConnectionRequest req = (key.isValid() ? (ConnectionRequest)key.attachment() : null);
		if (req != null && currentTime >= req.deadline && req.deadline > 0) {
			close(key);
			req.setException(new ConnectException("connection timed out"));
		}
	}
}
 
Example 6
Source File: SelectorManager.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
private void renewSelector()
{
    try
    {
        synchronized (this)
        {
            Selector selector=_selector;
            if (selector==null)
                return;
            final Selector new_selector = Selector.open();
            for (SelectionKey k: selector.keys())
            {
                if (!k.isValid() || k.interestOps()==0)
                    continue;

                final SelectableChannel channel = k.channel();
                final Object attachment = k.attachment();

                if (attachment==null)
                    addChange(channel);
                else
                    addChange(channel,attachment);
            }
            _selector.close();
            _selector=new_selector;
        }
    }
    catch(IOException e)
    {
        throw new RuntimeException("recreating selector",e);
    }
}
 
Example 7
Source File: TNonblockingServer.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Select and process IO events appropriately:
 * If there are connections to be accepted, accept them.
 * If there are existing connections with data waiting to be read, read it,
 * buffering until a whole frame has been read.
 * If there are any pending responses, buffer them until their target client
 * is available, and then send the data.
 */
private void select() {
  try {
    // wait for io events.
    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 the key is marked Accept, then it has to be the server
      // transport.
      if (key.isAcceptable()) {
        handleAccept();
      } else 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);
  }
}
 
Example 8
Source File: SelectorImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public void registerInterestOps(EventHandler eventHandler)
{
    if (orb.transportDebugFlag) {
        dprint(".registerInterestOps:-> " + eventHandler);
    }

    SelectionKey selectionKey = eventHandler.getSelectionKey();
    if (selectionKey.isValid()) {
        int ehOps = eventHandler.getInterestOps();
        SelectionKeyAndOp keyAndOp = new SelectionKeyAndOp(selectionKey, ehOps);
        synchronized(interestOpsList) {
            interestOpsList.add(keyAndOp);
        }
        // tell Selector Thread there's an update to a SelectorKey's Ops
        selector.wakeup();
    }
    else {
        wrapper.selectionKeyInvalid(eventHandler.toString());
        if (orb.transportDebugFlag) {
            dprint(".registerInterestOps: EventHandler SelectionKey not valid " + eventHandler);
        }
    }

    if (orb.transportDebugFlag) {
        dprint(".registerInterestOps:<- ");
    }
}
 
Example 9
Source File: NIOSocketWR.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
private void clearSelectionKey() {
    try {
        SelectionKey key = this.processKey;
        if (key != null && key.isValid()) {
            key.attach(null);
            key.cancel();
        }
    } catch (Exception e) {
        AbstractConnection.LOGGER.info("clear selector keys err:" + e);
    }
}
 
Example 10
Source File: TThreadedSelectorServerWithFix.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
/**
 * Select and process IO events appropriately: If there are existing
 * connections with data waiting to be read, read it, buffering until a
 * whole frame has been read. If there are any pending responses, buffer
 * them until their target client is available, and then send the data.
 */
private void select() {
  try {
    // wait for io events.
    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);
  }
}
 
Example 11
Source File: SelectorManager.java    From WebSocket-for-Android with Apache License 2.0 5 votes vote down vote up
private void renewSelector()
{
    try
    {
        synchronized (this)
        {
            Selector selector=_selector;
            if (selector==null)
                return;
            final Selector new_selector = Selector.open();
            for (SelectionKey k: selector.keys())
            {
                if (!k.isValid() || k.interestOps()==0)
                    continue;

                final SelectableChannel channel = k.channel();
                final Object attachment = k.attachment();

                if (attachment==null)
                    addChange(channel);
                else
                    addChange(channel,attachment);
            }
            _selector.close();
            _selector=new_selector;
        }
    }
    catch(IOException e)
    {
        throw new RuntimeException("recreating selector",e);
    }
}
 
Example 12
Source File: MainIOLoop.java    From aion with MIT License 5 votes vote down vote up
private static void processSelectedKey(SelectionKey key, ChannelBuffer buffer) {
    Task t = buffer.task;
    int state = 0;
    try {
        t.channelReady(key.channel(), key);
        state = 1;
    } catch (Throwable th) {

        // if this was an excepted exception
        if (th instanceof Exception) {
            // on any exception, drop
            key.cancel();
            t.channelUnregistered(key.channel(), th);
            state = 2;
        }

        // otherwise if this was a runtime exception, it could be that
        // our decoding logic is currently flawed, log out and ignore
        System.out.println("Selector caught unhandled exception");
        th.printStackTrace();
    } finally {
        // this should not happen, but handle anyways
        if (state == 0) {
            key.cancel();
            t.channelUnregistered(key.channel(), null);
        } else if (state == 1) {
            // if the task cancelled the key
            if (!key.isValid()) t.channelUnregistered(key.channel(), null);
        }
    }
}
 
Example 13
Source File: NioSocketConnector.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected ConnectionRequest getConnectionRequest(SocketChannel handle) {
    SelectionKey key = handle.keyFor(selector);

    if ((key == null) || (!key.isValid())) {
        return null;
    }

    return (ConnectionRequest) key.attachment();
}
 
Example 14
Source File: SelectorImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void registerInterestOps(EventHandler eventHandler)
{
    if (orb.transportDebugFlag) {
        dprint(".registerInterestOps:-> " + eventHandler);
    }

    SelectionKey selectionKey = eventHandler.getSelectionKey();
    if (selectionKey.isValid()) {
        int ehOps = eventHandler.getInterestOps();
        SelectionKeyAndOp keyAndOp = new SelectionKeyAndOp(selectionKey, ehOps);
        synchronized(interestOpsList) {
            interestOpsList.add(keyAndOp);
        }
        // tell Selector Thread there's an update to a SelectorKey's Ops
        try {
            if (selector != null) {
                // wakeup Selector thread to process close request
                selector.wakeup();
            }
        } catch (Throwable t) {
            if (orb.transportDebugFlag) {
                dprint(".registerInterestOps: selector.wakeup: ", t);
            }
        }
    }
    else {
        wrapper.selectionKeyInvalid(eventHandler.toString());
        if (orb.transportDebugFlag) {
            dprint(".registerInterestOps: EventHandler SelectionKey not valid " + eventHandler);
        }
    }

    if (orb.transportDebugFlag) {
        dprint(".registerInterestOps:<- ");
    }
}
 
Example 15
Source File: ExtendedWorker.java    From rapidoid with Apache License 2.0 5 votes vote down vote up
private void clearKey(SelectionKey key) throws IOException {
	if (key.isValid()) {
		SocketChannel socketChannel = (SocketChannel) key.channel();
		socketChannel.close();
		key.attach(null);
		key.cancel();
	}
}
 
Example 16
Source File: AcceptReadWriteDispatcherImpl.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Process Pending Close connections and then dispatch <code>Selector</code>
 * selected-key set.
 * 
 * @see com.aionemu.commons.network.Dispatcher#dispatch()
 */
@Override
void dispatch() throws IOException {
	int selected = selector.select();

	processPendingClose();

	if (selected != 0) {
		Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator();
		while (selectedKeys.hasNext()) {
			SelectionKey key = selectedKeys.next();
			selectedKeys.remove();

			if (!key.isValid())
				continue;

			/** Check what event is available and deal with it */
			switch (key.readyOps()) {
			case SelectionKey.OP_ACCEPT:
				this.accept(key);
				break;
			case SelectionKey.OP_READ:
				this.read(key);
				break;
			case SelectionKey.OP_WRITE:
				this.write(key);
				break;
			case SelectionKey.OP_READ | SelectionKey.OP_WRITE:
				this.read(key);
				if (key.isValid())
					this.write(key);
				break;
			}
		}
	}
}
 
Example 17
Source File: NonBlockingServer.java    From netty.book.kor with MIT License 4 votes vote down vote up
private void startServer() throws IOException {
    // create selector and channel
    this.selector = Selector.open();
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);

    // bind to port
    InetSocketAddress listenAddr = new InetSocketAddress(this.addr, this.port);
    serverChannel.socket().bind(listenAddr);
    serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);

    // processing
    while (true) {
        // wait for events
        this.selector.select();

        // wakeup to work on selected keys
        Iterator<SelectionKey> keys = this.selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = (SelectionKey) keys.next();

            // this is necessary to prevent the same key from coming up
            // again the next time around.
            keys.remove();

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

            if (key.isAcceptable()) {
                this.accept(key);
            }
            else if (key.isReadable()) {
                this.read(key);
            }
            else if (key.isWritable()) {
                this.write(key);
            }
        }
    }
}
 
Example 18
Source File: NIOConnector.java    From Mycat2 with GNU General Public License v3.0 4 votes vote down vote up
private void clearSelectionKey(SelectionKey key) {
	if (key.isValid()) {
		key.attach(null);
		key.cancel();
	}
}
 
Example 19
Source File: NIOLooper.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
public boolean isChannelValid(SelectableChannel channel) {
  SelectionKey key = channel.keyFor(selector);
  return key != null && key.isValid();
}
 
Example 20
Source File: AbstractDebugServer.java    From unidbg with Apache License 2.0 4 votes vote down vote up
private void runServer() {
    selector = null;
    serverSocketChannel = null;
    socketChannel = null;
    try {
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.socket().bind(new InetSocketAddress(DEFAULT_PORT));

        selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    } catch(IOException ex) {
        throw new IllegalStateException(ex);
    }

    serverShutdown = false;
    serverRunning = true;

    System.err.println("Start " + this + " server on port: " + DEFAULT_PORT);
    onServerStart();

    while(serverRunning) {
        try {
            int count = selector.select(50);
            if (count <= 0) {
                if (!isDebuggerConnected() && System.in.available() > 0) {
                    String line = new Scanner(System.in).nextLine();
                    if ("c".equals(line)) {
                        serverRunning = false;
                        break;
                    } else {
                        System.out.println("c: continue");
                    }
                }
                continue;
            }

            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = selectedKeys.next();
                if (key.isValid()) {
                    if (key.isAcceptable()) {
                        onSelectAccept(key);
                    }
                    if (key.isReadable()) {
                        onSelectRead(key);
                    }
                    if (key.isWritable()) {
                        onSelectWrite(key);
                    }
                }
                selectedKeys.remove();
            }

            processInput(input);
        } catch(Throwable e) {
            if (log.isDebugEnabled()) {
                log.debug("run server ex", e);
            }
        }
    }

    IOUtils.closeQuietly(serverSocketChannel);
    serverSocketChannel = null;
    IOUtils.closeQuietly(selector);
    selector = null;
    closeSocketChannel();
    resumeRun();
}