Example usage for java.nio.channels SelectionKey OP_WRITE

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

Introduction

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

Prototype

int OP_WRITE

To view the source code for java.nio.channels SelectionKey OP_WRITE.

Click Source Link

Document

Operation-set bit for write operations.

Usage

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    for (int i = 0; i < data.length; i++)
        data[i] = (byte) i;

    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);//  w  w  w. ja v a 2  s .c om

    server.socket().bind(new InetSocketAddress(9000));
    Selector selector = Selector.open();
    server.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = (SelectionKey) iterator.next();
            iterator.remove();
            if (key.isAcceptable()) {
                SocketChannel client = server.accept();
                System.out.println("Accepted connection from " + client);
                client.configureBlocking(false);
                ByteBuffer source = ByteBuffer.wrap(data);
                SelectionKey key2 = client.register(selector, SelectionKey.OP_WRITE);
                key2.attach(source);
            } else if (key.isWritable()) {
                SocketChannel client = (SocketChannel) key.channel();
                ByteBuffer output = (ByteBuffer) key.attachment();
                if (!output.hasRemaining()) {
                    output.rewind();
                }
                client.write(output);
            }
            key.channel().close();
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InetAddress serverIPAddress = InetAddress.getByName("localhost");
    int port = 19000;
    InetSocketAddress serverAddress = new InetSocketAddress(serverIPAddress, port);
    Selector selector = Selector.open();
    SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);//from   w  w  w. j  a v a2 s . c  o m
    channel.connect(serverAddress);
    int operations = SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    channel.register(selector, operations);

    userInputReader = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        if (selector.select() > 0) {
            boolean doneStatus = processReadySet(selector.selectedKeys());
            if (doneStatus) {
                break;
            }
        }
    }
    channel.close();
}

From source file:com.ok2c.lightmtp.impl.protocol.OutputTrigger.java

private void resume() {
    synchronized (this.state) {
        this.iosession.setEvent(SelectionKey.OP_WRITE);
    }
}

From source file:org.apache.axis2.transport.nhttp.LoggingIOSession.java

private static String formatOps(int ops) {
    StringBuffer buffer = new StringBuffer(6);
    buffer.append('[');
    if ((ops & SelectionKey.OP_READ) > 0) {
        buffer.append('r');
    }//from   ww  w.  j a  va  2 s.  co m
    if ((ops & SelectionKey.OP_WRITE) > 0) {
        buffer.append('w');
    }
    if ((ops & SelectionKey.OP_ACCEPT) > 0) {
        buffer.append('a');
    }
    if ((ops & SelectionKey.OP_CONNECT) > 0) {
        buffer.append('c');
    }
    buffer.append(']');
    return buffer.toString();
}

From source file:com.ok2c.lightmtp.impl.protocol.LoggingIOSession.java

private static String formatOps(final int ops) {
    final StringBuilder buffer = new StringBuilder(6);
    buffer.append('[');
    if ((ops & SelectionKey.OP_READ) > 0) {
        buffer.append('r');
    }//  w  w  w.  j a  v  a  2 s  .co m
    if ((ops & SelectionKey.OP_WRITE) > 0) {
        buffer.append('w');
    }
    if ((ops & SelectionKey.OP_ACCEPT) > 0) {
        buffer.append('a');
    }
    if ((ops & SelectionKey.OP_CONNECT) > 0) {
        buffer.append('c');
    }
    buffer.append(']');
    return buffer.toString();
}

From source file:com.ok2c.lightmtp.impl.protocol.ServiceShutdownCodec.java

@Override
public void reset(final IOSession iosession, final ServerState sessionState)
        throws IOException, SMTPProtocolException {
    this.writer.reset();
    this.pendingReply = new SMTPReply(SMTPCodes.ERR_TRANS_SERVICE_NOT_AVAILABLE, new SMTPCode(4, 3, 0),
            sessionState.getServerId() + " service shutting down " + "and closing transmission channel");
    this.completed = false;

    iosession.setEventMask(SelectionKey.OP_WRITE);
}

From source file:com.ok2c.lightmtp.impl.protocol.SendQuitCodec.java

@Override
public void reset(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    this.parser.reset();
    this.writer.reset();
    this.codecState = CodecState.QUIT_READY;

    iosession.setEvent(SelectionKey.OP_WRITE);
}

From source file:com.ok2c.lightmtp.impl.protocol.SendRsetCodec.java

@Override
public void reset(final IOSession iosession, final ClientState sessionState)
        throws IOException, SMTPProtocolException {
    this.parser.reset();
    this.writer.reset();
    this.codecState = CodecState.RSET_READY;

    iosession.setEvent(SelectionKey.OP_WRITE);
}

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 w w  . j a va 2 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());
}

From source file:de.kapsi.net.daap.nio.DaapConnectionNIO.java

/**
 * What do you do next?/*from  w  w w  .  ja  va  2s. c o  m*/
 *
 * @return
 */
int interrestOps() {

    if (isUndef()) {
        return SelectionKey.OP_READ;

    } else if (isDaapConnection()) {

        int op = SelectionKey.OP_READ;

        if (!writer.isEmpty())
            op |= SelectionKey.OP_WRITE;

        return op;

    } else {
        // isAudioStream
        return SelectionKey.OP_WRITE;
    }
}