List of usage examples for java.nio.channels SelectionKey cancel
public abstract void cancel();
From source file:HttpDownloadManager.java
void handleError(DownloadImpl download, SocketChannel channel, SelectionKey key, Throwable throwable) { download.status = Status.ERROR;/*from www .j a va 2 s.co m*/ try { if (channel != null) channel.close(); } catch (IOException e) { } if (key != null) key.cancel(); log.log(Level.WARNING, "Error connecting to or downloading from " + download.host + ":" + download.port, throwable); if (download.listener != null) download.listener.error(download, throwable); }
From source file:de.kapsi.net.daap.nio.DaapServerNIO.java
/** * Cancel SelesctionKey, close Channel and "free" the attachment *///from w ww.ja v a 2s . c om private void cancel(SelectionKey sk) { sk.cancel(); SelectableChannel channel = (SelectableChannel) sk.channel(); try { channel.close(); } catch (IOException err) { LOG.error("Channel.close()", err); } DaapConnection connection = (DaapConnection) sk.attachment(); if (connection != null) { DaapSession session = connection.getSession(false); if (session != null) { sessionIds.remove(session.getSessionId()); } connection.close(); if (connection.isDaapConnection()) { connections.remove(connection); } else if (connection.isAudioStream()) { streams.remove(connection); } } }
From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java
final void unregisterChannel(final SelectableChannel channel) { try {/*w ww. jav a 2 s .c om*/ final Selector selector = this.selector; if (selector != null) { if (channel != null) { final SelectionKey key = channel.keyFor(selector); if (key != null) { key.cancel(); this.cancelledKeys++; } } } if (channel != null && channel.isOpen()) { channel.close(); } } catch (final Throwable t) { // ignore } this.wakeup(); }
From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java
/** * Unlike the client side the read on the server will happen using receiving thread. *//*from ww w . j a va 2 s. c om*/ @Override void read(SelectionKey selectionKey, ByteBuffer replyBuffer) throws IOException { ReplyPostProcessor replyCallbackHandler = ((ReplyPostProcessor) this.replyCallbackMap.remove(selectionKey)); if (logger.isDebugEnabled()) { logger.debug("Reply received from " + ((SocketChannel) selectionKey.channel()).getRemoteAddress()); } if (this.replyListener != null) { this.replyListener.onReply(replyBuffer); } replyCallbackHandler.postProcess(replyBuffer); if (this.finite) { selectionKey.cancel(); this.closeChannel(selectionKey.channel()); this.onDisconnect(selectionKey); } }
From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java
final void dispatchEvent(final Set<SelectionKey> selectedKeySet) { final Iterator<SelectionKey> it = selectedKeySet.iterator(); boolean skipOpRead = false; // ? while (it.hasNext()) { final SelectionKey key = it.next(); it.remove();/*w w w . ja v a 2 s .c o m*/ if (!key.isValid()) { if (key.attachment() != null) { this.controller.closeSelectionKey(key); } else { key.cancel(); } continue; } try { if (key.isAcceptable()) { this.controller.onAccept(key); continue; } if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // Remove write interest key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); this.controller.onWrite(key); if (!this.controller.isHandleReadWriteConcurrently()) { skipOpRead = true; } } if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // read key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); // ??? if (!this.controller.getStatistics().isReceiveOverFlow()) { // Remove read interest this.controller.onRead(key);// ? continue; } else { key.interestOps(key.interestOps() // | SelectionKey.OP_READ); } } if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) { this.controller.onConnect(key); continue; } } catch (final RejectedExecutionException e) { // ??? if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.notifyException(e); if (this.selector.isOpen()) { continue; } else { break; } } catch (final CancelledKeyException e) { // ignore } catch (final Exception e) { if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.closeSelectionKey(key); this.controller.notifyException(e); log.error("Reactor dispatch events error", e); if (this.selector.isOpen()) { continue; } else { break; } } } }
From source file:com.taobao.gecko.core.nio.impl.Reactor.java
final void dispatchEvent(final Set<SelectionKey> selectedKeySet) { final Iterator<SelectionKey> it = selectedKeySet.iterator(); boolean skipOpRead = false; // while (it.hasNext()) { final SelectionKey key = it.next(); it.remove();// w w w .j a va 2 s . c o m if (!key.isValid()) { if (key.attachment() != null) { this.controller.closeSelectionKey(key); } else { key.cancel(); } continue; } try { if (key.isAcceptable()) { this.controller.onAccept(key); continue; } if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // Remove write interest key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE); this.controller.onWrite(key); if (!this.controller.isHandleReadWriteConcurrently()) { skipOpRead = true; } } if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // read key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); // if (!this.controller.getStatistics().isReceiveOverFlow()) { // Remove read interest this.controller.onRead(key);// continue; } else { key.interestOps(key.interestOps() // | SelectionKey.OP_READ); } } if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) { this.controller.onConnect(key); continue; } } catch (final RejectedExecutionException e) { // if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.notifyException(e); if (this.selector.isOpen()) { continue; } else { break; } } catch (final CancelledKeyException e) { // ignore } catch (final Exception e) { if (key.attachment() instanceof AbstractNioSession) { ((AbstractSession) key.attachment()).onException(e); } this.controller.closeSelectionKey(key); this.controller.notifyException(e); log.error("Reactor dispatch events error", e); if (this.selector.isOpen()) { continue; } else { break; } } } }
From source file:ca.wumbo.doommanager.server.ServerManager.java
/** * Kills any connections that have not sent any messages for a period of * time./*from w ww . j av a 2 s . c o m*/ * * @return * True if there was no error, false if an error occured. */ private boolean killInactiveConnections() { // Go through each connection every so often to check for dead connections. if (System.currentTimeMillis() - lastTimeoutCheckMillis > TIMEOUT_FREQUENCY_CHECK_MILLIS) { lastTimeoutCheckMillis = System.currentTimeMillis(); log.trace("Checking for timeouts... {}", System.currentTimeMillis()); // We cannot do this if the selector is closed. if (selector.isOpen()) { // Go through each connection... for (SelectionKey key : selector.keys()) { // If the attachment has client info (which it always should)... if (key.attachment() instanceof ClientInfo) { ClientInfo clientInfo = (ClientInfo) key.attachment(); // If the client hasn't responded for a certain amount of time, kill the connection. if (clientInfo.hasReceivedMessageSince(TIMEOUT_CLIENT_MILLIS)) { log.info("Client {} timed out, requesting connection termination.", clientInfo.getIPAddress()); Channel channel = key.channel(); key.cancel(); try { channel.close(); } catch (IOException e) { log.error("Error closing a timed out client's channel: {}", e.getMessage()); } } } } } } // Signal all is good. return true; }
From source file:net.socket.nio.TimeClientHandle.java
private void handleInput(SelectionKey key) throws IOException { if (key.isValid()) { // ??// ww w. jav a 2s. c om SocketChannel sc = (SocketChannel) key.channel(); if (key.isConnectable()) { if (sc.finishConnect()) { sc.register(selector, SelectionKey.OP_READ); doWrite(sc); } else { System.exit(1);// } } if (key.isReadable()) { ByteBuffer readBuffer = ByteBuffer.allocate(1024); int readBytes = sc.read(readBuffer); if (readBytes > 0) { readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; readBuffer.get(bytes); String body = new String(bytes, "UTF-8"); System.out.println("Now is : " + body); this.stop = true; } else if (readBytes < 0) { // key.cancel(); sc.close(); } else { ; // 0 } } } }
From source file:me.xingrz.prox.tcp.tunnel.Tunnel.java
/** * Selector OP_READ //from w w w . j a v a2 s .c o m * * @param key Selection Key */ @Override public final void onReadable(SelectionKey key) { if (closed || receiving == null) { return; } receiving.clear(); int read; try { read = channel.read(receiving); } catch (IOException e) { logger.w(e, "Failed to read from channel, terminated"); IOUtils.closeQuietly(this); return; } if (read == -1) { IOUtils.closeQuietly(this); return; } receiving.flip(); // if (!receiving.hasRemaining()) { return; } // ??? if (afterReceived(receiving)) { return; } // ?? if (!receiving.hasRemaining()) { return; } brother.beforeSending(receiving); if (!brother.write(receiving)) { logger.v("Brother not ready for receiving, canceled"); key.cancel(); } }
From source file:com.byteatebit.nbserver.simple.SelectorTask.java
protected void executeIoTasksOnSelectedKeys() { Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove();// w ww .j a va 2s . c o m try { NioSelectionKeyEntry nioTaskEntry = (NioSelectionKeyEntry) selectionKey.attachment(); if (nioTaskEntry == null) { LOG.error("The nio task is unexpectedly null for selectionKey " + selectionKey); return; } nioTaskEntry.executeTasks(selectionKey); } catch (Exception e) { LOG.error("Failed to execute the consumer attached to selectionKey " + selectionKey + ". Cancelling the key and closing the underlying channel", e); try { selectionKey.channel().close(); } catch (IOException e1) { LOG.error("selection key channel error on close", e); } selectionKey.cancel(); } } }