Example usage for java.nio.channels SelectionKey channel

List of usage examples for java.nio.channels SelectionKey channel

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey channel.

Prototype

public abstract SelectableChannel channel();

Source Link

Document

Returns the channel for which this key was created.

Usage

From source file:Main.java

public static String processRead(SelectionKey key) throws Exception {
    SocketChannel sChannel = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    sChannel.read(buffer);// www . j  a v a2s . c o  m
    buffer.flip();
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buffer);
    String msg = charBuffer.toString();
    return msg;
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

private static void closeSelector(Selector selector, SocketChannel selectedChannel) throws IOException {
    for (SelectionKey key : selector.keys()) {
        if (selectedChannel == null || !selectedChannel.equals(key.channel())) {
            closeQuietly(key.channel());
        }//ww  w .jav a 2  s  .com
    }

    selector.close();
}

From source file:org.sipfoundry.sipxbridge.symmitron.DataShuffler.java

/**
 * /*w  w  w  . ja va  2 s. co m*/
 * Implements the following search algorithm to retrieve a datagram channel that is associated
 * with the far end:
 * 
 * <pre>
 * getSelfRoutedDatagramChannel(farEnd)
 * For each selectable key do:
 *   let ipAddress be the local ip address
 *   let p be the local port
 *   let d be the datagramChannel associated with the key
 *   If  farEnd.ipAddress == ipAddress  &amp;&amp; port == localPort return d
 * return null
 * </pre>
 * 
 * @param farEnd
 * @return
 */

public static DatagramChannel getSelfRoutedDatagramChannel(InetSocketAddress farEnd) {
    // Iterate over the set of keys for which events are
    // available
    InetAddress ipAddress = farEnd.getAddress();
    int port = farEnd.getPort();
    for (Iterator<SelectionKey> selectedKeys = selector.keys().iterator(); selectedKeys.hasNext();) {
        SelectionKey key = selectedKeys.next();
        if (!key.isValid()) {
            continue;
        }
        DatagramChannel datagramChannel = (DatagramChannel) key.channel();
        if (datagramChannel.socket().getLocalAddress().equals(ipAddress)
                && datagramChannel.socket().getLocalPort() == port) {
            return datagramChannel;
        }

    }
    return null;

}

From source file:Main.java

public static boolean processReadySet(Set readySet) throws Exception {
    Iterator iterator = readySet.iterator();
    while (iterator.hasNext()) {
        SelectionKey key = (SelectionKey) iterator.next();
        iterator.remove();/*w w w  .  j a  va 2 s .c  om*/
        if (key.isConnectable()) {
            boolean connected = processConnect(key);
            if (!connected) {
                return true; // Exit
            }
        }
        if (key.isReadable()) {
            String msg = processRead(key);
            System.out.println("[Server]: " + msg);
        }
        if (key.isWritable()) {
            System.out.print("Please enter a message(Bye to quit):");
            String msg = userInputReader.readLine();

            if (msg.equalsIgnoreCase("bye")) {
                return true; // Exit
            }
            SocketChannel sChannel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
            sChannel.write(buffer);
        }
    }
    return false; // Not done yet
}

From source file:me.xingrz.prox.udp.UdpProxySession.java

@Override
public void onReadable(SelectionKey key) {
    udpProxy.receive((DatagramChannel) key.channel(), this);
}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

private static final void processWrite(SelectionKey key) throws Exception {
    Object att = key.attachment();
    if (att == null) {
        Thread.sleep(100);// w ww.j a v  a 2  s .co m
        return;
    }
    if (att instanceof ByteBuffer) {
        ByteBuffer buffer = (ByteBuffer) att;
        if (!buffer.hasRemaining()) {
            key.attach(new byte[0]);
            key.interestOps(SelectionKey.OP_READ);
            return;
        }
        SocketChannel channel = (SocketChannel) key.channel();
        channel.write(buffer);
    }
}

From source file:com.l2jfree.network.mmocore.AbstractSelectorThread.java

private void close() {
    for (SelectionKey key : getSelector().keys()) {
        IOUtils.closeQuietly(key.channel());
    }//from w ww .j a  v  a  2  s  .c o  m

    try {
        getSelector().close();
    } catch (IOException e) {
        // ignore
    }
}

From source file:com.l2jfree.network.mmocore.AcceptorThread.java

private void acceptConnection(SelectionKey key) {
    SocketChannel sc;// w  ww .j  a  v  a2  s.  c  om
    try {
        while ((sc = ((ServerSocketChannel) key.channel()).accept()) != null) {
            if (getMMOController().acceptConnectionFrom(sc)) {
                sc.configureBlocking(false);

                Util.printSection(getMMOController().getClass().getSimpleName() + " "
                        + sc.socket().getRemoteSocketAddress().toString());
                final T con = getMMOController().createClient(sc);
                con.enableReadInterest();
            } else {
                IOUtils.closeQuietly(sc.socket());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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  va  2 s. co  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/*w w w .  ja  va2 s .c  om*/
        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());
}