List of usage examples for java.nio.channels SelectionKey isReadable
public final boolean isReadable()
From source file:org.apache.htrace.impl.PackedBufferManager.java
private void doRecv(SelectionKey sockKey, ByteBuffer response) throws IOException { sockKey.interestOps(SelectionKey.OP_READ); SocketChannel sock = (SocketChannel) sockKey.attachment(); int totalRead = response.remaining(); long startMs = TimeUtil.nowMs(); long remainingMs = conf.ioTimeoutMs; while (remainingMs > 0) { selector.select(remainingMs);/* w w w. j a v a 2s . c om*/ for (SelectionKey key : selector.selectedKeys()) { if (key.isReadable()) { sock.read(response); } } if (response.remaining() == 0) { if (LOG.isTraceEnabled()) { LOG.trace("Received all " + totalRead + " bytes from " + conf.endpointStr); } return; } remainingMs = updateRemainingMs(startMs, conf.ioTimeoutMs); if (LOG.isTraceEnabled()) { LOG.trace("Received " + (totalRead - response.remaining()) + " out of " + totalRead + " bytes from " + conf.endpointStr); } if (remainingMs == 0) { throw new IOException("Attempt to write to " + conf.endpointStr + " timed out after " + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms."); } } }
From source file:idgs.client.TcpClient.java
private synchronized void select() throws IOException { if (timeout > 0) { if (selector.select(timeout) == 0) { throw new SocketTimeoutException(); }//w w w . j a va2 s .c o m } else { selector.select(); } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); // handle connect if (key.isConnectable()) { processConnect(key); } // handle read else if (key.isReadable()) { processRead(key); } // handle write else if (key.isWritable()) { processWrite(key); } it.remove(); } }
From source file:com.offbynull.portmapper.common.UdpCommunicator.java
@Override protected void run() throws Exception { ByteBuffer recvBuffer = ByteBuffer.allocate(1100); while (true) { selector.select();/*from www . jav a 2 s . c o m*/ if (stopFlag) { return; } for (DatagramChannel channel : sendQueue.keySet()) { if (!sendQueue.get(channel).isEmpty()) { channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); } else { channel.register(selector, SelectionKey.OP_READ); } } for (SelectionKey key : selector.selectedKeys()) { if (!key.isValid()) { continue; } DatagramChannel channel = (DatagramChannel) key.channel(); if (key.isReadable()) { recvBuffer.clear(); InetSocketAddress incomingAddress = (InetSocketAddress) channel.receive(recvBuffer); recvBuffer.flip(); for (UdpCommunicatorListener listener : listeners) { try { listener.incomingPacket(incomingAddress, channel, recvBuffer.asReadOnlyBuffer()); } catch (RuntimeException re) { // NOPMD // do nothing } } } else if (key.isWritable()) { LinkedBlockingQueue<ImmutablePair<InetSocketAddress, ByteBuffer>> queue = sendQueue .get(channel); ImmutablePair<InetSocketAddress, ByteBuffer> next = queue.poll(); if (next != null) { try { channel.send(next.getValue(), next.getKey()); } catch (RuntimeException re) { // NOPMD // do nothing } } } } } }
From source file:voldemort.common.nio.AbstractSelectorManager.java
public void run() { threadName = Thread.currentThread().getName(); try {/* w ww. j a v a 2 s . co m*/ while (true) { if (isClosed.get()) { logger.debug("SelectorManager is closed, exiting"); break; } lastHeartBeatTimeMs = System.currentTimeMillis(); processEvents(); try { selectTimeMs = System.currentTimeMillis(); int selected = selector.select(SELECTOR_POLL_MS); selectTimeMs = System.currentTimeMillis() - selectTimeMs; selectCount = selected; if (isClosed.get()) { logger.debug("SelectorManager is closed, exiting"); break; } if (selected > 0) { processingTimeMs = System.currentTimeMillis(); Iterator<SelectionKey> i = selector.selectedKeys().iterator(); while (i.hasNext()) { SelectionKey selectionKey = i.next(); i.remove(); if (selectionKey.isValid() && (selectionKey.isConnectable() || selectionKey.isReadable() || selectionKey.isWritable())) { Runnable worker = (Runnable) selectionKey.attachment(); worker.run(); } } processingTimeMs = System.currentTimeMillis() - processingTimeMs; } } catch (ClosedSelectorException e) { logger.debug("SelectorManager is closed, exiting"); break; } catch (Throwable t) { if (logger.isEnabledFor(Level.ERROR)) logger.error(t.getMessage(), t); } } } catch (Throwable t) { if (logger.isEnabledFor(Level.ERROR)) logger.error(t.getMessage(), t); } finally { try { close(); } catch (Exception e) { if (logger.isEnabledFor(Level.ERROR)) logger.error(e.getMessage(), e); } } }
From source file:org.cloudata.core.commitlog.WorkerPool.java
private void dispatchSelectedKeys() { Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove();// ww w. j ava 2s . c om if (key.isValid()) { if (key.isReadable()) { handleData(key); } else if (key.isConnectable()) { handleConnection(key); } else if (key.isWritable()) { handleWrite(key); } } } }
From source file:net.sf.cindy.impl.SimpleEventGenerator.java
protected void processKey(SelectionKey key) { SessionSpi session = (SessionSpi) key.attachment(); if (key.isAcceptable()) session.onEvent(Constants.EV_ACCEPTABLE, null); if (key.isConnectable()) session.onEvent(Constants.EV_CONNECTABLE, null); if (key.isValid() && key.isReadable()) session.onEvent(Constants.EV_READABLE, null); if (key.isValid() && key.isWritable()) session.onEvent(Constants.EV_WRITABLE, null); }
From source file:net.socket.nio.TimeClientHandle.java
private void handleInput(SelectionKey key) throws IOException { if (key.isValid()) { // ??//from w w w. j a v a2s . co m 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:org.pvalsecc.comm.MultiplexedServer.java
public void run() { try {//from w w w .j a v a2 s. c o m createSocket(); synchronized (socketCreatedLock) { socketCreated = true; socketCreatedLock.notifyAll(); } while (!stop) { int nbKeys = 0; try { nbKeys = selector.select(); } catch (IOException e) { LOGGER.error(e); } if (nbKeys > 0) { Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); if (key.isAcceptable()) { createNewClientConnection(key); } else if (key.isWritable()) { long startTime = System.nanoTime(); readyToSend(key); timeSending += System.nanoTime() - startTime; } else if (key.isReadable()) { long startTime = System.nanoTime(); readyToReceive(key); timeReceiving += System.nanoTime() - startTime; } it.remove(); } } } } catch (RuntimeException ex) { LOGGER.error("The MultiplexedServer [" + threadName + "] caught an unexpected exception.", ex); fatalErrorReporter.report(ex); } finally { if (selector != null) { for (SelectionKey key : selector.keys()) { SystemUtilities.safeClose(key.channel()); } SystemUtilities.safeClose(selector); } LOGGER.info("[" + threadName + "] inTime=" + UnitUtilities.toElapsedNanoTime(timeReceiving) + " outTime=" + UnitUtilities.toElapsedNanoTime(timeSending) + " in=" + nbBytesReceived + "B out=" + UnitUtilities.toComputerSize(nbBytesSent) + "B inNb=" + nbReceived + " outNb=" + nbSent); } }
From source file:gridool.communication.transport.nio.GridNioServer.java
public void accept(@Nonnull final Selector selector) throws IOException { while (!closed && selector.select() > 0) { for (Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); iter.hasNext();) { SelectionKey key = iter.next(); iter.remove();//w w w . j a va2 s . c o m if (!key.isValid()) { // Is key closed? if (LOG.isDebugEnabled()) { LOG.debug("Non valid key was detected. Key is already closed?"); } continue; } if (key.isAcceptable()) { ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); handleAccept(serverChannel, selector); } else if (key.isReadable()) { SocketChannel channel = (SocketChannel) key.channel(); handleRead(channel, key, sharedReadBuf, notifier, execPool); } } } if (LOG.isInfoEnabled()) { LOG.info("GridNioServer is going to be closed"); } this.closed = true; if (selector.isOpen()) { for (SelectionKey key : selector.keys()) { NIOUtils.close(key); } selector.close(); } }
From source file:edu.tsinghua.lumaqq.qq.net.Porter.java
/** * ??IPort./*from w w w . j a va 2s .c om*/ * ???//. * @see IPort#send(ByteBuffer) * @see IPort#receive(ByteBuffer) * @see IPort#maintain() */ @Override public void run() { log.debug("Porter??"); int n = 0; while (!shutdown) { // do select try { n = selector.select(3000); // ?shutdownselector if (shutdown) { selector.close(); break; } } catch (IOException e) { log.error(e.getMessage()); dispatchErrorToAll(e); } // ? processDisposeQueue(); // select0? if (n > 0) { for (Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext();) { // Key SelectionKey sk = i.next(); i.remove(); // ? if (!sk.isValid()) continue; // ? INIOHandler handler = (INIOHandler) sk.attachment(); try { if (sk.isConnectable()) handler.processConnect(sk); else if (sk.isReadable()) handler.processRead(sk); } catch (IOException e) { log.error(e.getMessage()); handler.processError(e); } catch (PacketParseException e) { log.debug("?: " + e.getMessage()); } catch (RuntimeException e) { log.error(e.getMessage()); } } n = 0; } checkNewConnection(); notifySend(); } selector = null; shutdown = false; log.debug("Porter?"); }