List of usage examples for java.nio.channels SelectionKey isValid
public abstract boolean isValid();
From source file:com.l2jfree.network.mmocore.ReadWriteThread.java
@Override protected void handle(SelectionKey key) { System.out.println("ReadWriteThread.handle() " + describeInterestOps(key.interestOps()) + ", ready: " + describeInterestOps(key.readyOps())); switch (key.readyOps()) { case SelectionKey.OP_CONNECT: finishConnection(key);/*from ww w. ja v a 2s . co m*/ break; case SelectionKey.OP_READ: readPacket(key); break; case SelectionKey.OP_WRITE: writePacket(key); break; case SelectionKey.OP_READ | SelectionKey.OP_WRITE: writePacket(key); // key might have been invalidated on writePacket if (key.isValid()) readPacket(key); break; default: System.err.println("Unknown readyOps: " + key.readyOps() + " for " + key.attachment()); break; } }
From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java
@Override public void run() { while (!this.isInterrupted()) { synchronized (this.pendingReadEventSubscribeRequests) { while (!this.pendingReadEventSubscribeRequests.isEmpty()) { final SelectionKey key = this.pendingReadEventSubscribeRequests.poll(); final IncomingConnection incomingConnection = (IncomingConnection) key.attachment(); final SocketChannel socketChannel = (SocketChannel) key.channel(); try { final SelectionKey newKey = socketChannel.register(this.selector, SelectionKey.OP_READ); newKey.attach(incomingConnection); } catch (ClosedChannelException e) { incomingConnection.reportTransmissionProblem(key, e); }// w ww . ja va2 s .com } } try { this.selector.select(500); } catch (IOException e) { LOG.error(e); } final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator(); while (iter.hasNext()) { final SelectionKey key = iter.next(); iter.remove(); if (key.isValid()) { if (key.isReadable()) { doRead(key); } else if (key.isAcceptable()) { doAccept(key); } else { LOG.error("Unknown key: " + key); } } else { LOG.error("Received invalid key: " + key); } } } // Do cleanup, if necessary if (this.listeningSocket != null) { try { this.listeningSocket.close(); } catch (IOException ioe) { // Actually, we can ignore this exception LOG.debug(ioe); } } // Finally, close the selector try { this.selector.close(); } catch (IOException ioe) { LOG.debug(StringUtils.stringifyException(ioe)); } }
From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java
private void dispatch() throws IOException { logger.debug("try dispatch"); SelectionKey key = null; for (SocketChannelOPSChangeRequest request : opsChangeRequstMap.values()) { key = request.getChannel().keyFor(selector); if (key != null) { // //from w ww. ja v a2 s. com if ((request.getOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { key.interestOps(SelectionKey.OP_WRITE); request.clearOps(SelectionKey.OP_WRITE); } else if ((request.getOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { key.interestOps(SelectionKey.OP_READ); request.clearOps(SelectionKey.OP_READ); } } } isWeakuped.set(false); if (selector.select(WaveriderConfig.WAVERIDER_DEFAULT_NETWORK_TIME_OUT) <= 0) { return; } Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { key = (SelectionKey) iterator.next(); iterator.remove(); try { if (!key.isValid()) { continue; } else if (key.isAcceptable()) { onAccept(key); } else if (key.isReadable()) { //readerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_READ)); onRead(key); } else if (key.isWritable()) { //writerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_WRITE)); onWrite(key); } } catch (IOException e) { // opsChangeRequstMap.remove((SocketChannel) key.channel()); Session session = (Session) key.attachment(); if (session != null) { session.onException(e); // Session sessionManager.freeSession(session); } key.cancel(); key.channel().close(); e.printStackTrace(); logger.error("OOPSException", e); } } }
From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java
/** * ?, ?, ?, ??/* w w w . j a v a2 s .c o m*/ * @throws IOException * @throws InterruptedException */ private void dispatch() throws IOException, InterruptedException { logger.debug("try dispatch"); SelectionKey key = null; key = opsChangeRequest.getChannel().keyFor(selector); if (key != null) { if ((opsChangeRequest.getOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { // key.interestOps(SelectionKey.OP_WRITE); opsChangeRequest.clearOps(SelectionKey.OP_WRITE); } else if ((opsChangeRequest.getOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { key.interestOps(SelectionKey.OP_READ); opsChangeRequest.clearOps(SelectionKey.OP_READ); } } // ?, isWeakuped.set(false); if (selector.select(WaveriderConfig.WAVERIDER_DEFAULT_NETWORK_TIME_OUT) <= 0) { return; } // ? Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while (iterator.hasNext()) { key = (SelectionKey) iterator.next(); iterator.remove(); if (!key.isValid()) { continue; } else if (key.isReadable()) { onRead(key); } else if (key.isWritable()) { onWrite(key); } } }
From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java
@Override public void run() { while (!isInterrupted()) { synchronized (this.pendingConnectionRequests) { if (!this.pendingConnectionRequests.isEmpty()) { final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll(); try { final SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT); socketChannel.connect(outgoingConnection.getConnectionAddress()); key.attach(outgoingConnection); } catch (final IOException ioe) { // IOException is reported by separate thread to avoid deadlocks final Runnable reporterThread = new Runnable() { @Override public void run() { outgoingConnection.reportConnectionProblem(ioe); }/* w ww . j av a2 s . com*/ }; new Thread(reporterThread).start(); } } } synchronized (this.pendingWriteEventSubscribeRequests) { if (!this.pendingWriteEventSubscribeRequests.isEmpty()) { final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll(); final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment(); final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel(); try { final SelectionKey newSelectionKey = socketChannel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); newSelectionKey.attach(outgoingConnection); outgoingConnection.setSelectionKey(newSelectionKey); } catch (final IOException ioe) { // IOException is reported by separate thread to avoid deadlocks final Runnable reporterThread = new Runnable() { @Override public void run() { outgoingConnection.reportTransmissionProblem(ioe); } }; new Thread(reporterThread).start(); } } } synchronized (this.connectionsToClose) { final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet() .iterator(); final long now = System.currentTimeMillis(); while (closeIt.hasNext()) { final Map.Entry<OutgoingConnection, Long> entry = closeIt.next(); if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) { final OutgoingConnection outgoingConnection = entry.getKey(); closeIt.remove(); // Create new thread to close connection to avoid deadlocks final Runnable closeThread = new Runnable() { @Override public void run() { try { outgoingConnection.closeConnection(); } catch (IOException ioe) { outgoingConnection.reportTransmissionProblem(ioe); } } }; new Thread(closeThread).start(); } } } try { this.selector.select(10); } catch (IOException e) { LOG.error(e); } final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator(); while (iter.hasNext()) { final SelectionKey key = iter.next(); iter.remove(); if (key.isValid()) { if (key.isConnectable()) { doConnect(key); } else { if (key.isReadable()) { doRead(key); // A read will always result in an exception, so the write key will not be valid anymore continue; } if (key.isWritable()) { doWrite(key); } } } else { LOG.error("Received invalid key: " + key); } } } // Finally, try to close the selector try { this.selector.close(); } catch (IOException ioe) { LOG.debug(StringUtils.stringifyException(ioe)); } }
From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java
private void closeSocketChannel(AbstractSelectableChannel channel, Selector selector) { try {//from w w w . ja v a 2s . c om SelectionKey sk = channel.keyFor(selector); if (sk != null && sk.isValid()) sk.cancel(); if (channel.isOpen()) channel.close(); } catch (Exception e) { log.error("Could not close channel : " + e.toString()); } }
From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java
protected void addInterest(AbstractSelectableChannel channel, int interest, Object attachment, Selector selector) {/* w w w .j a v a 2s.c o m*/ try { SelectionKey sk = channel.keyFor(selector); if (sk != null) { if (!sk.isValid()) return; int actualInterests = sk.interestOps(); if ((actualInterests & interest) != interest) sk.interestOps(actualInterests | interest); if (attachment != null) sk.attach(attachment); } else channel.register(selector, interest, attachment); } catch (ClosedChannelException e) { log.warn("Cannot add interest to selector channel : channel is closed"); } }
From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java
private void removeInterest(AbstractSelectableChannel channel, int interest, Selector selector) { SelectionKey sk = channel.keyFor(selector); if (sk != null && sk.isValid()) { int actualInterests = sk.interestOps(); if ((actualInterests & interest) != 0) sk.interestOps(sk.interestOps() & ~interest); }//from ww w.j av a 2 s.com }
From source file:net.ymate.platform.serv.nio.support.NioEventProcessor.java
@Override public void run() { try {/*from w ww. jav a 2s. co m*/ while (__flag) { __selector.select(5 * DateTimeUtils.SECOND); __doRegisterEvent(); Iterator<SelectionKey> _keyIterator = __selector.selectedKeys().iterator(); while (_keyIterator.hasNext()) { SelectionKey _selectionKey = _keyIterator.next(); _keyIterator.remove(); if (_selectionKey.isValid()) { Object _attachment = _selectionKey.attachment(); if (_attachment instanceof INioSession) { ((INioSession) _attachment).touch(); } try { if (_selectionKey.isAcceptable()) { __doAcceptEvent(_selectionKey); } else if (_selectionKey.isConnectable()) { __doConnectEvent(_selectionKey); } else if (_selectionKey.isReadable()) { __doReadEvent(_selectionKey); } else if (_selectionKey.isWritable()) { __doWriteEvent(_selectionKey); } } catch (Throwable e) { __doExceptionEvent(_selectionKey, e); } } } __doClosedEvent(); } } catch (IOException e) { if (__flag) { _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } else { _LOG.debug(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } }
From source file:org.apache.axis2.transport.udp.IODispatcher.java
/** * Run the I/O dispatcher./*from www . j a va 2 s . c om*/ * This method contains the event loop that polls the selector, reads the incoming * packets and dispatches the work. * It only returns when {@link #stop()} is called. */ public void run() { while (true) { try { selector.select(); } catch (IOException ex) { log.error("Exception in select; I/O dispatcher will be shut down", ex); return; } // Execute pending selector operations while (true) { SelectorOperation request = selectorOperationQueue.poll(); if (request == null) { break; } request.execute(selector); if (!selector.isOpen()) { return; } } for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext();) { SelectionKey key = it.next(); it.remove(); if (key.isValid() && key.isReadable()) { receive((Endpoint) key.attachment(), (DatagramChannel) key.channel()); } } } }