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:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void afterReadyInterestIsCleared() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);/*from   w w w . j a  v a2s  .  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
                }
            } 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.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    try {
        assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
        fail("Expected time-out");
    } catch (SocketTimeoutException e) {
        assertThat(e.getMessage(), containsString("timed out"));
    }
    hub.hub().addInterestAccept(key.get());
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:gobblin.tunnel.TunnelTest.java

@Test
public void mustHandleClientDisconnectingWithoutClosingTunnel() throws Exception {
    mockExample();/* w  w  w .j  av a2s.  co m*/
    Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);

    try {
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer
                .wrap("GET / HTTP/1.1%nUser-Agent: GobblinTunnel%nConnection:keep - alive %n%n".getBytes()));
        client.close();

        assertNotNull(fetchContent(tunnelPort));
    } finally {
        tunnel.close();
    }
}

From source file:org.apache.gobblin.tunnel.TunnelTest.java

@Test(enabled = false)
public void mustHandleClientDisconnectingWithoutClosingTunnel() throws Exception {
    mockExample();//from  w w w .  jav  a2  s. c  o  m
    Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);

    try {
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer
                .wrap("GET / HTTP/1.1%nUser-Agent: GobblinTunnel%nConnection:keep - alive %n%n".getBytes()));
        client.close();

        assertNotNull(fetchContent(tunnelPort));
    } finally {
        tunnel.close();
    }
}

From source file:org.jenkinsci.remoting.protocol.IOHubTest.java

@Test
public void noReadyCallbackIfInterestRemoved() throws Exception {
    final ServerSocketChannel srv = ServerSocketChannel.open();
    srv.bind(new InetSocketAddress(0));
    srv.configureBlocking(false);/*from   w  ww  . j  av a 2s .c o m*/
    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) {

        }
    });

    // Wait for registration, in other case we get unpredictable timing related results due to late registration
    while (key.get() == null) {
        Thread.sleep(10);
    }

    Socket client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #1"));
    hub.hub().removeInterestAccept(key.get());
    // wait for the interest accept to be removed
    while ((key.get().interestOps() & SelectionKey.OP_ACCEPT) != 0) {
        Thread.sleep(10);
    }
    client = new Socket();
    client.setSoTimeout(100);
    client.connect(srv.getLocalAddress(), 100);
    try {
        assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
        fail("Expected time-out");
    } catch (SocketTimeoutException e) {
        assertThat(e.getMessage(), containsString("timed out"));
    }
    hub.hub().addInterestAccept(key.get());
    assertThat(IOUtils.toString(client.getInputStream()), is("Go away #2"));
    assertThat("Only ever called ready with accept true", oops.get(), is(false));
}

From source file:org.quickserver.util.io.ByteBufferOutputStream.java

private synchronized void writeLastByteBuffer() throws IOException {
    int written = 0;
    while (lastByteBuffer.remaining() != 0) {
        java.nio.channels.SocketChannel sc = handler.getSocketChannel();
        if (sc != null && sc.isOpen()) {
            written = sc.write(lastByteBuffer);
            if (written == 0) {
                break;
            }//from   w  ww  .  jav a 2 s . c o m
            if (logger.isLoggable(Level.FINEST)) {
                logger.finest("Written " + written + " bytes");
            }
        } else {
            throw new IOException("SocketChannel was closed.");
        }
    }
    if (lastByteBuffer.remaining() == 0) {
        returnBufferBack(lastByteBuffer);
        lastByteBuffer = null;
    }
}

From source file:org.cloudata.core.commitlog.pipe.Message.java

public boolean write(SocketChannel channel) throws IOException {
    if (writingHeaderPhase) {
        ByteBuffer dupHeaderBuf = duplicate(headerBuf);
        dupHeaderBuf.position(writtenPosition);
        dupHeaderBuf.limit(headerBuf.capacity());
        channel.write(dupHeaderBuf);

        if (dupHeaderBuf.hasRemaining()) {
            writtenPosition = dupHeaderBuf.position();
            return false;
        }//from   w  w w.j a  va 2s .  c  om
        dupHeaderBuf.clear();
        writtenPosition = 0;
        writingHeaderPhase = false;
    }

    ByteBuffer dupBuffer = duplicate(buffer);
    dupBuffer.position(writtenPosition);
    dupBuffer.limit(buffer.capacity());
    channel.write(dupBuffer);

    if (dupBuffer.hasRemaining()) {
        writtenPosition = dupBuffer.position();
        return false;
    }

    writtenPosition = 0;
    writingHeaderPhase = true;
    dupBuffer.clear();
    return true;
}

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected void sendTo(int aPort, String anEncodedMessage) {
    SocketChannel socketChannel = null;

    try {//from  w  w w.  j av a2  s .c om
        socketChannel = SocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), aPort);
        socketChannel.connect(address);
        socketChannel.write(ByteBuffer.wrap(anEncodedMessage.getBytes()));
        logger.debug("Sent: {}", anEncodedMessage);

    } catch (IOException e) {
        logger.error("Failed to send because: {}: Continuing...", e.getMessage(), e);
    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                logger.error("Failed to close client socket because: {}: Continuing...", e.getMessage(), e);
            }
        }
    }
}

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  ava2s  .  c  om*/
        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:com.bittorrent.mpetazzoni.client.ConnectionHandler.java

/**
 * Send our handshake message to the socket.
 *
 * @param channel The socket channel to the remote peer.
 *///from w ww .  j  a v a  2s.  co m
private int sendHandshake(SocketChannel channel) throws IOException {
    return channel.write(
            Handshake.craft(this.torrent.getInfoHash(), this.id.getBytes(Torrent.BYTE_ENCODING)).getData());
}

From source file:com.p2p.peercds.client.ConnectionHandler.java

/**
 * Send our handshake message to the socket.
 *
 * @param channel The socket channel to the remote peer.
 *///from  w  w  w. j  a v  a  2  s .c  o  m
private int sendHandshake(SocketChannel channel) throws IOException {
    return channel
            .write(Handshake.craft(this.torrent.getInfoHash(), this.id.getBytes(BYTE_ENCODING)).getData());
}