private void onChannelAcceptable(SelectionKey key) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ); readKey.attach(key.attachment()); }
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); } } }
protected void cancel( SelectionKey key, SocketChannel c ) throws IOException { NioEndpoint p = (NioEndpoint)key.attachment(); log.log( Level.FINE, "Closing channel endpoint:{0}.", p ); Object o = endpointKeys.remove(p); log.log( Level.FINE, "Endpoint keys size:{0}", endpointKeys.size() ); key.cancel(); c.close(); removeEndpoint( p, c ); }
final SelectionKey k = i.next(); final Object a = k.attachment(); i.remove(); if (!i.hasNext()) { break; selectedKeys = selector.selectedKeys();
@Override public void run() { if (key != null && key.isValid()) { SocketChannel channel = (SocketChannel) key.channel(); Beat beat = (Beat) key.attachment(); if (channel.isConnected()) { return; } try { channel.finishConnect(); } catch (Exception ignore) { } try { beat.finishCheck(false, false, beat.getTask().getCheckRTNormalized() * 2, "tcp:timeout"); key.cancel(); key.channel().close(); } catch (Exception ignore) { } } } }
@Override public void process(SelectionKey key) throws IOException { SelectableChannel channel = key.channel(); if (!(channel instanceof SocketChannel)) { logger.warn("incorrect instance of channel. The key is cancelled"); key.cancel(); return; } SocketChannel socketChannel = (SocketChannel) channel; logger.trace("server {} get new data from {}", myServerSocketLocalAddress, socketChannel); Object attachment = key.attachment(); if (!(attachment instanceof ReadAttachment)) { logger.warn("incorrect instance of attachment for channel {}", new Object[]{socketChannel.socket()}); socketChannel.close(); return; } ConnectionListener connectionListener = ((ReadAttachment) attachment).getConnectionListener(); connectionListener.onNewDataAvailable(socketChannel); }
private void doAsyncWrite(SelectionKey key) throws IOException { SimpleServerRpcConnection connection = (SimpleServerRpcConnection) key.attachment(); if (connection == null) { throw new IOException("doAsyncWrite: no connection"); } if (key.channel() != connection.channel) { throw new IOException("doAsyncWrite: bad channel"); } if (processAllResponses(connection)) { try { // We wrote everything, so we don't need to be told when the socket is ready for // write anymore. key.interestOps(0); } catch (CancelledKeyException e) { /* * The Listener/reader might have closed the socket. We don't explicitly cancel the key, so * not sure if this will ever fire. This warning could be removed. */ SimpleRpcServer.LOG.warn("Exception while changing ops : " + e); } } }
@Override public void run() { final Selector selector = this.selector; for (;;) { ++connectCount; try { selector.select(1000L); connect(selector); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { Object att = key.attachment(); if (att != null && key.isValid() && key.isConnectable()) { finishConnect(key, att); } else { key.cancel(); } } } finally { keys.clear(); } } catch (Throwable e) { LOGGER.warn(name, e); } } }
for (SelectionKey key : oldSelector.selectedKeys()) { if (!key.isValid() && key.readyOps() == 0) continue; SelectableChannel channel = key.channel(); Object attachment = key.attachment();
/** * Execute a write operation * @param key the selectionkey to write on * @throws IOException if an error happened during batch */ private void doWrite(SelectionKey key) throws IOException { WebSocketImpl conn = (WebSocketImpl) key.attachment(); if( SocketChannelIOHelper.batch( conn, conn.getChannel() ) ) { if( key.isValid() ) { key.interestOps(SelectionKey.OP_READ); } } }
private void selectSocketChannelKeys() throws IOException { // once a channel associated with a key in this selector is 'ready', it causes this select to immediately return. // thus, for each trip through the run() we only get hit with one real timeout...the one in selectServerSocketKeys. int numSelected = socketChannelSelector.select(timeout); if (numSelected == 0) { return; } for (SelectionKey socketChannelKey : socketChannelSelector.selectedKeys()) { final SelectableChannel channel = socketChannelKey.channel(); AbstractChannelReader reader = null; // there are 2 kinds of channels in this selector, both which have their own readers and are executed in their own // threads. We will get here whenever a new SocketChannel is created due to an incoming connection. However, // for a DatagramChannel we don't want to create a new reader unless it is a new DatagramChannel. The only // way to tell if it's new is the lack of an attachment. if (channel instanceof DatagramChannel && socketChannelKey.attachment() == null) { reader = new DatagramChannelReader(UUID.randomUUID().toString(), socketChannelKey, emptyBuffers, factory, readSingleDatagram); socketChannelKey.attach(reader); final ScheduledFuture<?> readerFuture = executor.scheduleWithFixedDelay(reader, 10L, channelReaderFrequencyMilliseconds.get(), TimeUnit.MILLISECONDS); reader.setScheduledFuture(readerFuture); } if (reader != null && LOGGER.isDebugEnabled()) { LOGGER.debug(this + " New Connection established. Server channel: " + channel + " Reader: " + reader); } } }
private static void processConnectTimeout(Set<SelectionKey> keys, long currentTimeNanos) { for (SelectionKey k: keys) { if (!k.isValid()) { // Comment the close call again as it gave us major problems // with ClosedChannelExceptions. // // See: // * https://github.com/netty/netty/issues/142 // * https://github.com/netty/netty/issues/138 // // close(k); continue; } NioClientSocketChannel ch = (NioClientSocketChannel) k.attachment(); if (ch.connectDeadlineNanos > 0 && currentTimeNanos >= ch.connectDeadlineNanos) { // Create a new ConnectException everytime and not cache it as otherwise we end up with // using the wrong remoteaddress in the ConnectException message. // // See https://github.com/netty/netty/issues/2713 ConnectException cause = new ConnectTimeoutException("connection timed out: " + ch.requestedRemoteAddress); ch.connectFuture.setFailure(cause); fireExceptionCaught(ch, cause); ch.worker.close(ch, succeededFuture(ch)); } } }
final SelectionKey checkIfSpinnedKey(final SelectionKey key) { if (!key.isValid() && key.channel().isOpen() && spinnedSelectorsHistory.containsKey(key.selector())) { final SelectionKey newKey = key.channel().keyFor(getSelector()); newKey.attach(key.attachment()); return newKey; } return key; }
final SelectionKey k = i.next(); final Object a = k.attachment(); i.remove(); if (!i.hasNext()) { break; selectedKeys = selector.selectedKeys();
Object a = key.attachment(); try { if (!key.isValid() || key.channel().keyFor(newSelectorTuple.unwrappedSelector) != null) { continue; int interestOps = key.interestOps(); key.cancel(); SelectionKey newKey = key.channel().register(newSelectorTuple.unwrappedSelector, interestOps, a); if (a instanceof AbstractNioChannel) {
logger.trace("Closing SelectionKey's channel"); sk.channel().close(); Object attachment = sk.attachment(); if(attachment instanceof Closeable) { IOUtils.closeQuietly((Closeable) attachment); logger.trace("Cancelling SelectionKey"); sk.cancel(); } catch(Exception e) { if(logger.isEnabledFor(Level.WARN))
private void doAsyncWrite(SelectionKey key) throws IOException { RpcCall call = (RpcCall)key.attachment(); if (call == null) { return; } if (key.channel() != call.connection.channel) { throw new IOException("doAsyncWrite: bad channel"); } synchronized(call.connection.responseQueue) { if (processResponse(call.connection.responseQueue, false)) { try { key.interestOps(0); } catch (CancelledKeyException e) { /* The Listener/reader might have closed the socket. * We don't explicitly cancel the key, so not sure if this will * ever fire. * This warning could be removed. */ LOG.warn("Exception while changing ops : " + e); } } } }
selector.select(1000L); register(selector); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { Object att = key.attachment(); if (att != null && key.isValid()) { int readyOps = key.readyOps(); if ((readyOps & SelectionKey.OP_READ) != 0) { write((NIOConnection) att); } else { key.cancel(); key.cancel();
private void dispatch(SelectionKey selectionKey) { Callable<?> attachment = (Callable<?>) selectionKey.attachment(); try { attachment.call(); } catch (Exception e) { LOG.error("exception handling event on {}", selectionKey.channel(), e); } } }
/** * Iterate over the queue of connections ready to resume selection, * and restore their interest ops selection mask. */ private void processInterestOpsUpdateRequests() { SelectionKey key; while (!stopped && (key = updateQueue.poll()) != null) { if (!key.isValid()) { cleanupSelectionKey(key); } NIOServerCnxn cnxn = (NIOServerCnxn) key.attachment(); if (cnxn.isSelectable()) { key.interestOps(cnxn.getInterestOps()); } } } }