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

The following examples show how to use java.nio.channels.SelectionKey#attach() . 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: Test01.java    From jdk-source-analysis with Apache License 2.0 8 votes vote down vote up
@Override
public void run() {
    try {
        SocketChannel socketChannel = serverSocketChannel.accept();
        System.out.println(
                socketChannel.socket().getRemoteSocketAddress()
                        .toString() + " is connected.");
        if (Objects.nonNull(socketChannel)) {
            socketChannel.configureBlocking(false);
            SelectionKey selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);
            selector.wakeup();
            selectionKey.attach(new TCPHandler(selectionKey, socketChannel));
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: MultiThreadNIOEchoServer.java    From LearningOfThinkInJava with Apache License 2.0 8 votes vote down vote up
private void doAccept(SelectionKey sk){
    ServerSocketChannel server=(ServerSocketChannel)sk.channel();
    SocketChannel clientChannel;
    try {
        //获取客户端的channel
        clientChannel = server.accept();
        clientChannel.configureBlocking(false);

        //register the channel for reading
        SelectionKey clientKey=clientChannel.register(selector,SelectionKey.OP_READ);
        //Allocate an EchoClient instance and attach it to this selection key.
        EchoClient echoClient=new EchoClient();
        clientKey.attach(echoClient);

        InetAddress clientAddress=clientChannel.socket().getInetAddress();
        System.out.println("Accepted connetion from "+clientAddress.getHostAddress()+".");
    }catch (Exception e){
        System.out.println("Failed to accept new client");
        e.printStackTrace();
    }
}
 
Example 3
Source File: TAsyncMethodCall.java    From galaxy-sdk-java with Apache License 2.0 7 votes vote down vote up
/**
 * Register with selector and start first state, which could be either connecting or writing.
 * @throws IOException if register or starting fails
 */
void start(Selector sel) throws IOException {
  SelectionKey key;
  if (transport.isOpen()) {
    state = State.WRITING_REQUEST_SIZE;
    key = transport.registerSelector(sel, SelectionKey.OP_WRITE);
  } else {
    state = State.CONNECTING;
    key = transport.registerSelector(sel, SelectionKey.OP_CONNECT);

    // non-blocking connect can complete immediately,
    // in which case we should not expect the OP_CONNECT
    if (transport.startConnect()) {
      registerForFirstWrite(key);
    }
  }

  key.attach(this);
}
 
Example 4
Source File: NonBlockingServerWithOffLoopTasks.java    From tls-channel with MIT License 6 votes vote down vote up
private static void handleNewConnection(
    SSLContext sslContext, Selector selector, ServerSocketChannel serverChannel)
    throws IOException {
  // accept new connection
  SocketChannel rawChannel = serverChannel.accept();
  rawChannel.configureBlocking(false);

  // wrap raw channel in TlsChannel
  TlsChannel tlsChannel =
      ServerTlsChannel.newBuilder(rawChannel, sslContext).withRunTasks(false).build();

  /*
   * Wrap raw channel with a TlsChannel. Note that the raw channel is registered in the selector
   * and the TlsChannel put as an attachment register the channel for reading, because TLS
   * connections are initiated by clients.
   */
  SelectionKey newKey = rawChannel.register(selector, SelectionKey.OP_READ);
  newKey.attach(tlsChannel);
}
 
Example 5
Source File: EchoServer.java    From netty.book.kor with MIT License 6 votes vote down vote up
/**
 * Accept a new client and set it up for reading.
 */
private void doAccept(SelectionKey sk) {
    ServerSocketChannel server = (ServerSocketChannel) sk.channel();
    SocketChannel clientChannel;
    try {
        clientChannel = server.accept();
        clientChannel.configureBlocking(false);

        // Register this channel for reading.
        SelectionKey clientKey = clientChannel.register(selector, SelectionKey.OP_READ);

        // Allocate an EchoClient instance and attach it to this selection key.
        EchoClient echoClient = new EchoClient();
        clientKey.attach(echoClient);

        InetAddress clientAddress = clientChannel.socket().getInetAddress();
        System.out.println("Accepted connection from " + clientAddress.getHostAddress() + ".");
    }
    catch (Exception e) {
        System.out.println("Failed to accept new client.");
        e.printStackTrace();
    }

}
 
Example 6
Source File: TNonblockingServer.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
/**
 * Accept a new connection.
 */
private void handleAccept() throws IOException {
  SelectionKey clientKey = null;
  TNonblockingTransport client = null;
  try {
    // accept the connection
    client = (TNonblockingTransport)serverTransport.accept();
    clientKey = client.registerSelector(selector, SelectionKey.OP_READ);

    // add this key to the map
    FrameBuffer frameBuffer = new FrameBuffer(client, clientKey,
      SelectAcceptThread.this);
    clientKey.attach(frameBuffer);
  } catch (TTransportException tte) {
    // something went wrong accepting.
    LOGGER.warn("Exception trying to accept!", tte);
    tte.printStackTrace();
    if (clientKey != null) cleanupSelectionKey(clientKey);
    if (client != null) client.close();
  }
}
 
Example 7
Source File: RunLoop.java    From whiskey with Apache License 2.0 6 votes vote down vote up
/**
 * Registers socket events to be handled on the internal RunLoopThread. This method is
 * unsynchronized, and may block if not called from the internal RunLoopThread.
 */
@SuppressWarnings("ResourceType")
public void register(int interestSet, Selectable selectable) {
    if (interestSet == 0) {
        return;
    }

    try {
        SelectionKey key = selectable.getChannel().register(selector, interestSet);
        key.attach(selectable);
        // TODO: implement unregister and map the key internally instead of passing it back
        selectable.setSelectionKey(key);
    } catch(ClosedChannelException e) {
        selectable.onClose(e);
    }
}
 
Example 8
Source File: ServerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
void reRegister(HttpConnection c) {
   try {
      SocketChannel chan = c.getChannel();
      chan.configureBlocking(false);
      SelectionKey key = chan.register(ServerImpl.this.selector, 1);
      key.attach(c);
      c.selectionKey = key;
      c.time = ServerImpl.this.getTime() + ServerImpl.IDLE_INTERVAL;
      ServerImpl.this.idleConnections.add(c);
   } catch (IOException var4) {
      ServerImpl.dprint((Exception)var4);
      ServerImpl.this.logger.log(Level.FINER, "Dispatcher(8)", var4);
      c.close();
   }

}
 
Example 9
Source File: ReaderThread.java    From kieker with Apache License 2.0 6 votes vote down vote up
private void readFromSocket(final SelectionKey key) throws IOException {
	boolean endOfStreamReached = false;
	final Connection connection = (Connection) key.attachment();
	final SocketChannel socketChannel = connection.getChannel();

	int bytesRead = socketChannel.read(connection.getBuffer());

	while (bytesRead > 0) {
		bytesRead = socketChannel.read(connection.getBuffer());
	}
	if (bytesRead == -1) {
		endOfStreamReached = true;
	}

	this.processBuffer(connection);

	if (endOfStreamReached || connection.isError()) {
		this.logger.debug("Socket closed: " + socketChannel.getRemoteAddress().toString());
		key.attach(null);
		key.cancel();
		key.channel().close();
	}
}
 
Example 10
Source File: ServerSockerChannelTest.java    From jdk-source-analysis with Apache License 2.0 5 votes vote down vote up
public Reactor(int port, boolean isMaster) throws IOException {
    this.port = port;
    this.isMaster = isMaster;
    this.selector = Selector.open();
    if (isMaster) {
        serverSocket = ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(port));
        serverSocket.configureBlocking(false);
        SelectionKey selectionKey = this.serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        selectionKey.attach(new Object());
        System.out.println("start on " + port + " ...");
    } else {
        // TODO 如何
    }
}
 
Example 11
Source File: AbstractConnection.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
private void clearSelectionKey() {
    final Lock lock = this.keyLock;
    lock.lock();
    try {
        SelectionKey key = this.processKey;
        if (key != null && key.isValid()) {
            key.attach(null);
            key.cancel();
        }
    } finally {
        lock.unlock();
    }
}
 
Example 12
Source File: ZeroCopyConnection.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 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) {
		LOGGER.warn("clear selector keys err:" + e);
	}
}
 
Example 13
Source File: AbstractSelectableChannel.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Registers this channel with the given selector, returning a selection key.
 *
 * <p>  This method first verifies that this channel is open and that the
 * given initial interest set is valid.
 *
 * <p> If this channel is already registered with the given selector then
 * the selection key representing that registration is returned after
 * setting its interest set to the given value.
 *
 * <p> Otherwise this channel has not yet been registered with the given
 * selector, so the {@link AbstractSelector#register register} method of
 * the selector is invoked while holding the appropriate locks.  The
 * resulting key is added to this channel's key set before being returned.
 * </p>
 *
 * @throws  ClosedSelectorException {@inheritDoc}
 *
 * @throws  IllegalBlockingModeException {@inheritDoc}
 *
 * @throws  IllegalSelectorException {@inheritDoc}
 *
 * @throws  CancelledKeyException {@inheritDoc}
 *
 * @throws  IllegalArgumentException {@inheritDoc}
 */
public final SelectionKey register(Selector sel, int ops,
                                   Object att)
    throws ClosedChannelException
{
    synchronized (regLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if ((ops & ~validOps()) != 0)
            throw new IllegalArgumentException();
        if (isBlocking())
            throw new IllegalBlockingModeException();
        SelectionKey k = findKey(sel);
        if (k != null) {
            k.interestOps(ops);
            k.attach(att);
        }
        if (k == null) {
            // New registration
            synchronized (keyLock) {
                if (!isOpen())
                    throw new ClosedChannelException();
                k = ((AbstractSelector)sel).register(this, ops, att);
                addKey(k);
            }
        }
        return k;
    }
}
 
Example 14
Source File: SimpleRpcServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
private void closeCurrentConnection(SelectionKey key, Throwable e) {
  if (key != null) {
    SimpleServerRpcConnection c = (SimpleServerRpcConnection)key.attachment();
    if (c != null) {
      closeConnection(c);
      key.attach(null);
    }
  }
}
 
Example 15
Source File: NioClientProcessor.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
@Override
public void connect(SelectionKey key) {
    try {
        channel.socketChannel().finishConnect();
        key.attach(channel);
    } catch (IOException e) {
        eventHandler().exceptionCaught(channel, e);
        key.cancel();
        return;
    }
    key.interestOps(SelectionKey.OP_READ);
}
 
Example 16
Source File: NetworkSelector.java    From tribaltrouble with GNU General Public License v2.0 5 votes vote down vote up
final void attachToKey(SelectionKey key, Handler handler) {
	Object handler_key = null;
	if (!deterministic.isPlayback()) {
		handler_key = new Integer(current_handler_id++);
		key.attach(handler_key);
	}
	handler_key = deterministic.log(handler_key);
	handler_map.put(handler_key, handler);
}
 
Example 17
Source File: AbstractNonBlockingConnectionManager.java    From xenqtt with Apache License 2.0 5 votes vote down vote up
final void close(SocketChannel channel, SelectionKey key) {
	key.cancel();
	key.attach(null);
	try {
		channel.close();
	} catch (IOException ignore) {
	}
}
 
Example 18
Source File: AbstractSelectableChannel.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Registers this channel with the given selector, returning a selection key.
 *
 * <p>  This method first verifies that this channel is open and that the
 * given initial interest set is valid.
 *
 * <p> If this channel is already registered with the given selector then
 * the selection key representing that registration is returned after
 * setting its interest set to the given value.
 *
 * <p> Otherwise this channel has not yet been registered with the given
 * selector, so the {@link AbstractSelector#register register} method of
 * the selector is invoked while holding the appropriate locks.  The
 * resulting key is added to this channel's key set before being returned.
 * </p>
 *
 * @throws  ClosedSelectorException {@inheritDoc}
 *
 * @throws  IllegalBlockingModeException {@inheritDoc}
 *
 * @throws  IllegalSelectorException {@inheritDoc}
 *
 * @throws  CancelledKeyException {@inheritDoc}
 *
 * @throws  IllegalArgumentException {@inheritDoc}
 */
public final SelectionKey register(Selector sel, int ops,
                                   Object att)
    throws ClosedChannelException
{
    synchronized (regLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if ((ops & ~validOps()) != 0)
            throw new IllegalArgumentException();
        if (isBlocking())
            throw new IllegalBlockingModeException();
        SelectionKey k = findKey(sel);
        if (k != null) {
            k.interestOps(ops);
            k.attach(att);
        }
        if (k == null) {
            // New registration
            synchronized (keyLock) {
                if (!isOpen())
                    throw new ClosedChannelException();
                k = ((AbstractSelector)sel).register(this, ops, att);
                addKey(k);
            }
        }
        return k;
    }
}
 
Example 19
Source File: TAsyncMethodCall.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
private void cleanUpAndFireCallback(SelectionKey key) {
  state = State.RESPONSE_READ;
  key.interestOps(0);
  // this ensures that the TAsyncMethod instance doesn't hang around
  key.attach(null);
  client.onComplete();
  callback.onComplete((T)this);
}
 
Example 20
Source File: NioBlockingSelector.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void run() {
    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 {
            if (sk.isValid()) {
                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);
                }
            }else {
                sk.cancel();
                sk.attach(null);
            }
        }
    }catch (CancelledKeyException cx) {
        if (sk!=null) {
            sk.cancel();
            sk.attach(null);
        }
    }
}