List of usage examples for java.nio.channels SelectionKey isValid
public abstract boolean isValid();
From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java
private SelectionKey selectFirstConnectedSocketChannel(Selector selector) throws IOException { log.trace("selectFirstConnectedSocketChannel()"); while (!selector.keys().isEmpty()) { if (selector.select(connectTimeout) == 0) { // Block until something happens return null; }/*from www.ja va 2 s.c o m*/ Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey key = it.next(); if (key.isValid() && key.isConnectable()) { SocketChannel channel = (SocketChannel) key.channel(); try { if (channel.finishConnect()) { return key; } } catch (Exception e) { key.cancel(); closeQuietly(channel); log.trace("Error connecting socket channel: {}", e); } } it.remove(); } } return null; }
From source file:net.socket.nio.TimeClientHandle.java
private void handleInput(SelectionKey key) throws IOException { if (key.isValid()) { // ??//from ww w . j a v a 2 s . 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:com.byteatebit.nbserver.task.TestWriteMessageTask.java
@Test public void testWriteFailed() throws IOException { SocketChannel socket = mock(SocketChannel.class); ByteArrayOutputStream messageStream = new ByteArrayOutputStream(); String message = "hi\n"; when(socket.write(any(ByteBuffer.class))).thenThrow(new IOException("write failed")); INbContext nbContext = mock(INbContext.class); SelectionKey selectionKey = mock(SelectionKey.class); when(selectionKey.channel()).thenReturn(socket); when(selectionKey.isValid()).thenReturn(true); when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE); WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100)) .build();//from w w w . j a va2 s .c o m List<String> callbackInvoked = new ArrayList<>(); List<Exception> exceptionHandlerInvoked = new ArrayList<>(); Runnable callback = () -> callbackInvoked.add(""); Consumer<Exception> exceptionHandler = exceptionHandlerInvoked::add; writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback, exceptionHandler); verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any()); writeTask.write(selectionKey, callback, exceptionHandler); verify(selectionKey, times(1)).interestOps(0); Assert.assertEquals(0, messageStream.size()); Assert.assertEquals(0, callbackInvoked.size()); Assert.assertEquals(1, exceptionHandlerInvoked.size()); }
From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java
@Test public void testWriteCompleteMessage() throws IOException { SocketChannel socket = mock(SocketChannel.class); ByteArrayOutputStream messageStream = new ByteArrayOutputStream(); String message = "hi\n"; when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() { @Override/*from w ww . j ava2 s . c o m*/ public Integer answer(InvocationOnMock invocationOnMock) throws Throwable { ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0]; while (buffer.hasRemaining()) messageStream.write(buffer.get()); return buffer.position(); } }); INbContext nbContext = mock(INbContext.class); SelectionKey selectionKey = mock(SelectionKey.class); when(selectionKey.channel()).thenReturn(socket); when(selectionKey.isValid()).thenReturn(true); when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE); WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100)) .build(); List<String> callbackInvoked = new ArrayList<>(); Runnable callback = () -> callbackInvoked.add(""); Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage()); writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback, exceptionHandler); verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any()); writeTask.write(selectionKey, callback, exceptionHandler); verify(selectionKey, times(1)).interestOps(0); Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8)); Assert.assertEquals(1, callbackInvoked.size()); }
From source file:com.offbynull.portmapper.common.UdpCommunicator.java
@Override protected void run() throws Exception { ByteBuffer recvBuffer = ByteBuffer.allocate(1100); while (true) { selector.select();//ww w . j a v 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:com.byteatebit.nbserver.task.TestWriteMessageTask.java
@Test public void testWriteMessageInParts() throws IOException { SocketChannel socket = mock(SocketChannel.class); ByteArrayOutputStream messageStream = new ByteArrayOutputStream(); String messagePart1 = "messagePart1 "; String messagePart2 = "messagePart2"; String message = messagePart1 + messagePart2; when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() { @Override//from www . j av a2 s .co m public Integer answer(InvocationOnMock invocationOnMock) throws Throwable { ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0]; for (int i = 0; i < messagePart1.length(); i++) messageStream.write(buffer.get()); return messagePart1.length(); } }).then(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocationOnMock) throws Throwable { ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0]; for (int i = 0; i < messagePart2.length(); i++) messageStream.write(buffer.get()); return messagePart2.length(); } }); INbContext nbContext = mock(INbContext.class); SelectionKey selectionKey = mock(SelectionKey.class); when(selectionKey.channel()).thenReturn(socket); when(selectionKey.isValid()).thenReturn(true); when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE); WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100)) .build(); List<String> callbackInvoked = new ArrayList<>(); Runnable callback = () -> callbackInvoked.add(""); Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage()); writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback, exceptionHandler); verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any()); // simulate first write writeTask.write(selectionKey, callback, exceptionHandler); verify(selectionKey, times(0)).interestOps(0); // simulate second write writeTask.write(selectionKey, callback, exceptionHandler); verify(selectionKey, times(1)).interestOps(0); Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8)); Assert.assertEquals(1, callbackInvoked.size()); }
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();// ww w . j a v a2s. 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:com.byteatebit.nbserver.task.ReadDelimitedMessageTask.java
protected void read(SelectionKey selectionKey, Consumer<List<String>> callback, Consumer<Exception> exceptionHandler) { try {//from w w w. j av a 2s . c om if (!selectionKey.isValid() || !selectionKey.isReadable()) return; byteBuffer.clear(); int bytesRead = ((ReadableByteChannel) selectionKey.channel()).read(byteBuffer); if (bytesRead < 0) { LOG.warn( "End of stream reached. Deregistering interest in reads on the selection key invoking exception handler."); invokeExceptionHandler(selectionKey, exceptionHandler, new EOFException("End of stream")); return; } byteBuffer.flip(); if (byteBuffer.remaining() + messageBuffer.size() > maxMessageSize) { LOG.error("Max message size of " + maxMessageSize + " bytes exceeded. Deregistering interest in reads on the selection key invoking exception handler."); invokeExceptionHandler(selectionKey, exceptionHandler, new IllegalStateException("Max message size of " + maxMessageSize + " bytes exceeded")); return; } while (byteBuffer.hasRemaining()) messageBuffer.write(byteBuffer.get()); String messagesString = messageBuffer.toString(charset); messageBuffer.reset(); List<String> messages = new ArrayList<>(); for (String message : splitter.split(messagesString)) messages.add(message); messageBuffer.write(messages.remove(messages.size() - 1).getBytes(charset)); if (!messages.isEmpty()) { selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ); callback.accept(messages); } } catch (Exception e) { LOG.error("ReadDelimitedMessage task failed", e); invokeExceptionHandler(selectionKey, exceptionHandler, e); } }
From source file:org.reunionemu.jreunion.server.Network.java
@Override public void run() { logger.info("network thread starting"); while (true) { try {//from w w w.j av a 2 s. co m // See if we've had any activity -- either an incoming connection, // or incoming data on an existing connection int num = selector.select(); if (num == 0) { // we need synchronize here otherwise we might block again before we were able to change the selector synchronized (this) { continue; } } // If we don't have any activity, loop around and wait again // Get the keys corresponding to the activity // that has been detected, and process them one by one Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> it = keys.iterator(); while (it.hasNext()) { // Get a key representing one of bits of I/O activity SelectionKey key = it.next(); if (!key.isValid()) continue; SelectableChannel selectableChannel = key.channel(); // What kind of activity is it? if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { // It's an incoming connection. // Register this socket with the Selector // so we can listen for input on it SocketChannel clientSocketChannel = ((ServerSocketChannel) selectableChannel).accept(); processAccept(clientSocketChannel); } else { SocketChannel socketChannel = (SocketChannel) selectableChannel; if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // It's incoming data on a connection, so process it boolean ok = processInput(socketChannel); // If the connection is dead, then remove it // from the selector and close it if (!ok) { LoggerFactory.getLogger(Network.class).info("Client Connection Lost"); key.cancel(); disconnect(socketChannel); } } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { boolean ok = processOutput(socketChannel); if (ok) { socketChannel.register(selector, SelectionKey.OP_READ); } } } } // We remove the selected keys, because we've dealt with them. keys.clear(); } catch (Exception e) { if (e instanceof ClosedSelectorException || e instanceof InterruptedException) return; LoggerFactory.getLogger(Network.class).error("Error in network", e); } } }
From source file:edu.tsinghua.lumaqq.qq.net.Porter.java
/** * ??IPort./*from w w w. j a v a2s . co m*/ * ???//. * @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?"); }