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

The following examples show how to use java.nio.channels.SelectionKey#attachment() . 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: SimpleRpcServer.java    From hbase with Apache License 2.0 6 votes vote down vote up
void doRead(SelectionKey key) throws InterruptedException {
  int count;
  SimpleServerRpcConnection c = (SimpleServerRpcConnection) key.attachment();
  if (c == null) {
    return;
  }
  c.setLastContact(System.currentTimeMillis());
  try {
    count = c.readAndProcess();
  } catch (InterruptedException ieo) {
    LOG.info(Thread.currentThread().getName() + ": readAndProcess caught InterruptedException", ieo);
    throw ieo;
  } catch (Exception e) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Caught exception while reading:", e);
    }
    count = -1; //so that the (count < 0) block is executed
  }
  if (count < 0) {
    closeConnection(c);
    c = null;
  } else {
    c.setLastContact(System.currentTimeMillis());
  }
}
 
Example 2
Source File: MainIOLoop.java    From aion with MIT License 6 votes vote down vote up
private void processSelectedKeys() {
    Set<SelectionKey> selectedKeys = this.currSelector.selectedKeys();
    if (selectedKeys.isEmpty()) return;

    Iterator<SelectionKey> it = selectedKeys.iterator();
    while (true) {
        final SelectionKey key = it.next();
        final ChannelBuffer buffer = (ChannelBuffer) key.attachment();
        processSelectedKey(key, buffer);
        // remove the current key
        it.remove();

        if (!it.hasNext()) break;

        if (this.needsToSelectAgain) {
            selectAgain();
            Set<SelectionKey> keys = this.currSelector.selectedKeys();
            if (keys.isEmpty()) break;
            else it = selectedKeys.iterator();
        }
    }
}
 
Example 3
Source File: NioEventLoop.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
private void closeAll() {
    selectAgain();
    Set<SelectionKey> keys = selector.keys();
    Collection<AbstractNioChannel> channels = new ArrayList<AbstractNioChannel>(keys.size());
    for (SelectionKey k: keys) {
        Object a = k.attachment();
        if (a instanceof AbstractNioChannel) {
            channels.add((AbstractNioChannel) a);
        } else {
            k.cancel();
            @SuppressWarnings("unchecked")
            NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a;
            invokeChannelUnregistered(task, k, null);
        }
    }

    for (AbstractNioChannel ch: channels) {
        ch.unsafe().close(ch.unsafe().voidPromise());
    }
}
 
Example 4
Source File: NioProcessor.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * In the case we are using the java select() method, this method is used to
 * trash the buggy selector and create a new one, registering all the
 * sockets on it.
 */
@Override
protected void registerNewSelector() throws IOException {
    synchronized (selector) {
        Set<SelectionKey> keys = selector.keys();

        // Open a new selector
        Selector newSelector = Selector.open();

        // Loop on all the registered keys, and register them on the new selector
        for (SelectionKey key : keys) {
            SelectableChannel ch = key.channel();

            // Don't forget to attache the session, and back !
            NioSession session = (NioSession) key.attachment();
            SelectionKey newKey = ch.register(newSelector, key.interestOps(), session);
            session.setSelectionKey(newKey);
        }

        // Now we can close the old selector and switch it
        selector.close();
        selector = newSelector;
    }
}
 
Example 5
Source File: PollTcpManagerNio.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
private void wakeConnections(PortSocket port)
{
  for (SelectionKey key : _selector.keys()) {
    PollController conn = (PollController) key.attachment();
    
    if (conn != null && (port == null || conn.getPort() == port)) {
      key.cancel();
    
      remove(conn);

      try {
        conn.onPollReadClose();
      } catch (Throwable e) {
        log.log(Level.WARNING, e.toString(), e);
      }
    }
  }
}
 
Example 6
Source File: AsynchronousTlsChannelGroup.java    From tls-channel with MIT License 5 votes vote down vote up
private void processPendingInterests() {
  for (SelectionKey key : selector.keys()) {
    RegisteredSocket socket = (RegisteredSocket) key.attachment();
    int pending = socket.pendingOps.getAndSet(0);
    if (pending != 0) {
      key.interestOps(key.interestOps() | pending);
    }
  }
}
 
Example 7
Source File: ServerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private void handleException(SelectionKey key, Exception e) {
   HttpConnection conn = (HttpConnection)key.attachment();
   if (e != null) {
      ServerImpl.this.logger.log(Level.FINER, "Dispatcher (2)", e);
   }

   ServerImpl.this.closeConnection(conn);
}
 
Example 8
Source File: Relay.java    From gnirehtet with Apache License 2.0 5 votes vote down vote up
public void run() throws IOException {
    Selector selector = Selector.open();

    // will register the socket on the selector
    TunnelServer tunnelServer = new TunnelServer(port, selector);

    Log.i(TAG, "Relay server started");

    long nextCleaningDeadline = System.currentTimeMillis() + UDPConnection.IDLE_TIMEOUT;
    while (true) {
        long timeout = Math.max(0, nextCleaningDeadline - System.currentTimeMillis());
        selector.select(timeout);
        Set<SelectionKey> selectedKeys = selector.selectedKeys();

        long now = System.currentTimeMillis();
        if (now >= nextCleaningDeadline || selectedKeys.isEmpty()) {
            tunnelServer.cleanUp();
            nextCleaningDeadline = now + CLEANING_INTERVAL;
        }

        for (SelectionKey selectedKey : selectedKeys) {
            SelectionHandler selectionHandler = (SelectionHandler) selectedKey.attachment();
            selectionHandler.onReady(selectedKey);
        }
        // by design, we handled everything
        selectedKeys.clear();
    }
}
 
Example 9
Source File: NIOConnectionManager.java    From bt with Apache License 2.0 5 votes vote down vote up
void processSelected() throws IOException {
	Set<SelectionKey> keys = selector.selectedKeys();
	for(SelectionKey selKey : keys)
	{
		Selectable connection = (Selectable) selKey.attachment();
		connection.selectionEvent(selKey);
	}
	keys.clear();
}
 
Example 10
Source File: NIOLooper.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
/**
 * Register an operation interest on a SelectableChannel, with ISelectHandler as callback attachment
 * There are two cases when trying to register an interest
 * 1. The whole key does not exist; no interests ever registered for this channel
 * 2. The key exists due to other interests registered but not the one we are adding
 * <p>
 * In 1st case, we just register this channel with operation on the given Selector
 * In 2nd case, we have to make sure the state of NIOLooper is clean:
 * 1. Key has to be valid
 * 2. The interest has not yet been registered
 * 3. If old attached ISelectHandler exists, it has to be the same as new one
 * If any one of above 3 conditions are not met, RuntimeException would be thrown.
 *
 * @param channel The Selectable to register operation interest
 * @param operation The operation interest to register
 * @param callback The Callback to handle
 * @throws ClosedChannelException if Channel is closed when trying to register an interest
 */
private void addInterest(SelectableChannel channel,
                         int operation,
                         ISelectHandler callback)
    throws ClosedChannelException {

  SelectionKey key = channel.keyFor(selector);

  if (key == null) {
    channel.register(selector, operation, callback);
  } else if (!key.isValid()) {
    throw new RuntimeException(
        String.format("Unable to add %d in %s due to key is invalid", operation, channel));
  } else {
    // Key is not null and key is valid
    if ((key.interestOps() & operation) != 0) {
      throw new RuntimeException(
          String.format("%d has been registered in %s", operation, channel));
    }
    if (key.attachment() == null) {
      key.attach(callback);
    } else {
      if (callback != key.attachment()) {
        throw new RuntimeException("Unmatched SelectHandler has already been attached"
            + " for other operation");
      }
      // If call == key.attachment
      // Just skip
    }
    key.interestOps(key.interestOps() | operation);
  }
}
 
Example 11
Source File: NIOAcceptor.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 仅后台维护的主动创建的连接使用
 */
@SuppressWarnings("unchecked")
protected void processConnectKey(SelectionKey curKey) throws IOException {
    // only from cluster server socket
    SocketChannel curChannel = (SocketChannel) curKey.channel();
    Object obj = curKey.attachment();
    try {
        if (curChannel.finishConnect()) {
            throw new MycatException("unsupport!");
        }
    } catch (ConnectException ex) {
        LOGGER.warn("Connect failed:{}  message:{}", curChannel, ex);
    }
}
 
Example 12
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 13
Source File: UdpForwarder.java    From FwdPortForwardingApp with GNU General Public License v3.0 5 votes vote down vote up
public static void handleRead(SelectionKey key, ByteBuffer readBuffer) throws IOException {

        // Log.i("UdpForwarder", "Handling Read");
        DatagramChannel channel = (DatagramChannel) key.channel();
        ClientRecord clientRecord = (ClientRecord) key.attachment();

        // Ensure the buffer is empty
        readBuffer.clear();

        // Receive the data
        channel.receive(readBuffer);

        // Get read to wrte, then send
        readBuffer.flip();
        channel.send(readBuffer, clientRecord.toAddress);

        // If there is anything remaining in the buffer
        if (readBuffer.remaining() > 0) {
            clientRecord.writeBuffer.put(readBuffer);
            key.interestOps(SelectionKey.OP_WRITE);
        }

//        ClientRecord clientRecord = (ClientRecord) key.attachment();
//        clientRecord.buffer.clear();    // Prepare buffer for receiving
//        clientRecord.clientAddress = channel.receive(clientRecord.buffer);
//
//        if (clientRecord.clientAddress != null) {  // Did we receive something?
//            // Register write with the selector
//            key.interestOps(SelectionKey.OP_WRITE);
//        }
    }
 
Example 14
Source File: NioSelectorLoop.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
private void doWrite(SelectionKey key) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("doWrite:" + key.toString());
    }
    NioChannel channel = (NioChannel) key.attachment();
    processor.flush(channel);
}
 
Example 15
Source File: IOMultiplexEchoServer.java    From new-bull with MIT License 5 votes vote down vote up
private void onWritable(SelectionKey key) throws IOException {
    Client client = (Client) key.attachment();
    client.onWrite();
    if (client.state == Client.State.Finished) {
        client.close();
    }
}
 
Example 16
Source File: NioReceiver.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
protected void socketTimeouts() {
        long now = System.currentTimeMillis();
        if ( (now-lastCheck) < getSelectorTimeout() ) return;
        //timeout
        Selector tmpsel = this.selector.get();
        Set<SelectionKey> keys =  (isListening()&&tmpsel!=null)?tmpsel.keys():null;
        if ( keys == null ) return;
        for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) {
            SelectionKey key = iter.next();
            try {
//                if (key.interestOps() == SelectionKey.OP_READ) {
//                    //only timeout sockets that we are waiting for a read from
//                    ObjectReader ka = (ObjectReader) key.attachment();
//                    long delta = now - ka.getLastAccess();
//                    if (delta > (long) getTimeout()) {
//                        cancelledKey(key);
//                    }
//                }
//                else
                if ( key.interestOps() == 0 ) {
                    //check for keys that didn't make it in.
                    ObjectReader ka = (ObjectReader) key.attachment();
                    if ( ka != null ) {
                        long delta = now - ka.getLastAccess();
                        if (delta > getTimeout() && (!ka.isAccessed())) {
                            if (log.isWarnEnabled())
                                log.warn(sm.getString(
                                        "nioReceiver.threadsExhausted",
                                        Integer.valueOf(getTimeout()),
                                        Boolean.valueOf(ka.isCancelled()),
                                        key,
                                        new java.sql.Timestamp(ka.getLastAccess())));
                            ka.setLastAccess(now);
                            //key.interestOps(SelectionKey.OP_READ);
                        }//end if
                    } else {
                        cancelledKey(key);
                    }//end if
                }//end if
            }catch ( CancelledKeyException ckx ) {
                cancelledKey(key);
            }
        }
        lastCheck = System.currentTimeMillis();
    }
 
Example 17
Source File: TCPAcceptor.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void handleReadEvent(SelectionKey key) throws IOException {
    TCPSession session = (TCPSession) key.attachment();
    if (session == null) throw new RuntimeException("The session is null when reading data...");
    session.read();
}
 
Example 18
Source File: HTTPWriteHandler.java    From AdditionsAPI with MIT License 4 votes vote down vote up
@Override
public void handleSelection(SelectionKey selectionKey)
{
	if(selectionKey.isWritable())
	{
		HTTPResponse response = (HTTPResponse) selectionKey.attachment();
		SocketChannel channel = (SocketChannel) selectionKey.channel();
		
		if(response.buffer == null)
		{
			this.buildBuffer(response);
		}
		
		try
		{
			if(response.buffer.hasRemaining())
			{
				this.writeBuffer(channel, response);
			}
			else
			{
				if(response.context != null && response.contextPosition < response.context.getSize())
				{
					this.writeContext(channel, response);
				}
				else
				{
					if(server.debug)
					{
						Debug.sayTrue("");
						Debug.sayTrue("Response sent to: " + channel.getRemoteAddress());
						Debug.sayTrue(response.toString());
						Debug.sayTrue("");
					}
					this.closeChannel(selectionKey);
				}
			}
		}
		catch(IOException e)
		{
			this.closeChannel(selectionKey);
			if(server.debug)
			{
				e.printStackTrace();
			}
		}
		
	}
}
 
Example 19
Source File: AbstractNioWorker.java    From simple-netty-source with Apache License 2.0 4 votes vote down vote up
@Override
protected void close(SelectionKey k) {
    AbstractNioChannel<?> ch = (AbstractNioChannel<?>) k.attachment();
    close(ch, succeededFuture(ch));
}
 
Example 20
Source File: NioReplicationTask.java    From tomcatsrc with Apache License 2.0 3 votes vote down vote up
/**
 * Called to initiate a unit of work by this worker thread
 * on the provided SelectionKey object.  This method is
 * synchronized, as is the run() method, so only one key
 * can be serviced at a given time.
 * Before waking the worker thread, and before returning
 * to the main selection loop, this key's interest set is
 * updated to remove OP_READ.  This will cause the selector
 * to ignore read-readiness for this channel while the
 * worker thread is servicing it.
 */
public synchronized void serviceChannel (SelectionKey key) {
    if ( log.isTraceEnabled() ) log.trace("About to service key:"+key);
    ObjectReader reader = (ObjectReader)key.attachment();
    if ( reader != null ) reader.setLastAccess(System.currentTimeMillis());
    this.key = key;
    key.interestOps (key.interestOps() & (~SelectionKey.OP_READ));
    key.interestOps (key.interestOps() & (~SelectionKey.OP_WRITE));
}