Example usage for java.nio.channels SocketChannel write

List of usage examples for java.nio.channels SocketChannel write

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel write.

Prototype

public final long write(ByteBuffer[] srcs) throws IOException 

Source Link

Usage

From source file:reactor.io.net.http.PostAndGetTests.java

private void get(String path, SocketAddress address) {
    try {/*  w  ww  .  j av  a  2s  . c  om*/
        StringBuilder request = new StringBuilder().append(String.format("GET %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n").append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("get: request >> [%s]", request.toString()));
        channel.write(Buffer.wrap(request.toString()).byteBuffer());
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1)
            ;
        String response = new String(buf.array());
        System.out.println(String.format("get: << Response: %s", response));
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:reactor.io.netty.http.PostAndGetTests.java

private void post(String path, String data, SocketAddress address) {
    try {//from   ww  w  .java  2 s . c  o m
        StringBuilder request = new StringBuilder().append(String.format("POST %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n");
        request.append(String.format("Content-Length: %s\r\n", data.length())).append("\r\n").append(data)
                .append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("post: request >> [%s]", request.toString()));
        channel.write(ByteBuffer.wrap(request.toString().getBytes()));
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1)
            ;
        String response = new String(buf.array());
        System.out.println(String.format("post: << Response: %s", response));
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:reactor.io.net.http.PostAndGetTests.java

private void post(String path, String data, SocketAddress address) {
    try {/*from   w w w .  ja  v a2 s  .co m*/
        StringBuilder request = new StringBuilder().append(String.format("POST %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n");
        request.append(String.format("Content-Length: %s\r\n", data.length())).append("\r\n").append(data)
                .append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("post: request >> [%s]", request.toString()));
        channel.write(Buffer.wrap(request.toString()).byteBuffer());
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1)
            ;
        String response = new String(buf.array());
        System.out.println(String.format("post: << Response: %s", response));
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:reactor.ipc.netty.http.client.PostAndGetTests.java

private void get(String path, SocketAddress address) {
    try {//from www.  j a  v a 2  s . c om
        StringBuilder request = new StringBuilder().append(String.format("GET %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n").append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("get: request >> [%s]", request.toString()));
        channel.write(ByteBuffer.wrap(request.toString().getBytes()));
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1) {
        }
        String response = new String(buf.array());
        System.out.println(String.format("get: << Response: %s", response));
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:reactor.ipc.netty.http.client.PostAndGetTests.java

private void post(String path, String data, SocketAddress address) {
    try {/*from www.j av a 2 s .  co  m*/
        StringBuilder request = new StringBuilder().append(String.format("POST %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n");
        request.append(String.format("Content-Length: %s\r\n", data.length())).append("\r\n").append(data)
                .append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("post: request >> [%s]", request.toString()));
        channel.write(ByteBuffer.wrap(request.toString().getBytes()));
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1) {
        }
        String response = new String(buf.array());
        Loggers.getLogger(PostAndGetTests.class).info("post: << " + "Response: %s", response);
        channel.close();
    } 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();// w  w w . jav  a  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:idgs.client.SocketChannelHandler.java

/**
 * handle connect//from w w  w  . jav a  2  s . com
 * @throws IOException
 */
public void onConnected(SocketChannel channel) throws IOException {
    ClientLogin login = new ClientLogin();
    ByteBuffer buffer = login.toBuffer();
    buffer.flip();
    int writeClientLoginSize = channel.write(buffer);
    if (writeClientLoginSize > 0) {
        log.debug("writer client login content: " + new String(login.toString()));
        log.debug("byte size: " + writeClientLoginSize + ", order by " + RpcBuffer.DEFAULT_BYTE_ORDER.toString()
                + " bytes: " + Arrays.toString(buffer.array()));
    }
}

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 a  v a 2  s. co  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:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void canAcceptSocketConnections() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);/* w w w.j  a  v  a  2  s . c om*/
    final AtomicReference<SelectionKey> key = new AtomicReference<SelectionKey>();
    final AtomicBoolean oops = new AtomicBoolean(false);
    hub.hub().register(srv, new IOHubReadyListener() {

        final AtomicInteger count = new AtomicInteger(0);

        @Override
        public void ready(boolean accept, boolean connect, boolean read, boolean write) {
            if (accept) {
                try {
                    SocketChannel channel = srv.accept();
                    channel.write(ByteBuffer.wrap(String.format("Go away #%d", count.incrementAndGet())
                            .getBytes(Charset.forName("UTF-8"))));
                    channel.close();
                } catch (IOException e) {
                    // ignore
                }
                hub.hub().addInterestAccept(key.get());
            } else {
                oops.set(true);
            }
            if (connect || read || write) {
                oops.set(true);
            }
        }
    }, true, false, false, false, new IOHubRegistrationCallback() {
        @Override
        public void onRegistered(SelectionKey selectionKey) {
            key.set(selectionKey);
        }

        @Override
        public void onClosedChannel(ClosedChannelException e) {

        }
    });
    Socket client = new Socket();
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    client = new Socket();
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:net.socket.nio.TimeClientHandle.java

private void doWrite(SocketChannel sc) throws IOException {
    byte[] req = "QUERY TIME ORDER".getBytes();
    ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
    writeBuffer.put(req);/*from   w  w  w . ja va2 s. c o m*/
    writeBuffer.flip();
    sc.write(writeBuffer);
    sc.write(writeBuffer);
    if (!writeBuffer.hasRemaining()) {
        System.out.println("Send order 2 server succeed.");
    }
}