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.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(enabled = false, timeOut = 15000, expectedExceptions = IOException.class)
public void testTunnelThreadDeadAfterUnexpectedException() throws IOException, InterruptedException {
    MockServer proxyServer = startConnectProxyServer(false, false, 8);

    Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost",
            proxyServer.getServerSocketPort());

    String response = "";
    try {// ww w  .j av a  2  s.c o  m
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer.wrap("Knock\n".getBytes()));
        response = readFromSocket(client);
        LOG.info(response);

        for (int i = 0; i < 5; i++) {
            client.write(ByteBuffer.wrap("Hello\n".getBytes()));
            Thread.sleep(100);
        }
        client.close();
    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertNotEquals(response, "Knock Knock\n");
        assertEquals(proxyServer.getNumConnects(), 1);
        assertFalse(tunnel.isTunnelThreadAlive());
    }
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

private void runClientToTalkFirstServer(int tunnelPort) throws IOException {
    SocketChannel client = SocketChannel.open();

    client.connect(new InetSocketAddress("localhost", tunnelPort));
    String response0 = readFromSocket(client);
    LOG.info(response0);/* ww w  .j  a  va 2 s.c  o  m*/

    client.write(ByteBuffer.wrap("Knock\n".getBytes()));
    String response1 = readFromSocket(client);
    LOG.info(response1);

    client.write(ByteBuffer.wrap("Hello\n".getBytes()));
    String response2 = readFromSocket(client);
    LOG.info(response2);

    client.close();

    assertEquals(response0, "Hello\n");
    assertEquals(response1, "Knock Knock\n");
    assertEquals(response2, "Hello Hello\n");
}

From source file:org.reunionemu.jreunion.server.Network.java

private boolean processOutput(SocketChannel socketChannel) {

    Client client = Server.getInstance().getWorld().getClients().get(socketChannel);

    if (client == null)
        return false;

    if (!socketChannel.isOpen() || !socketChannel.isConnected()) {
        disconnect(socketChannel);/*from   ww  w . j a  v  a2  s  .  c  om*/
        return false;
    }
    buffer.clear();
    byte[] packetBytes = client.flush();
    if (packetBytes == null)
        return true;
    buffer.put(packetBytes);
    buffer.flip();

    try {
        socketChannel.write(buffer);
    } catch (IOException e) {
        LoggerFactory.getLogger(this.getClass()).error("Exception", e);
        disconnect(socketChannel);
        return false;
    }
    return true;
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(expectedExceptions = IOException.class)
public void testTunnelWhereProxyConnectionToServerFailsWithWriteFirstClient()
        throws IOException, InterruptedException {
    MockServer proxyServer = startConnectProxyServer();
    final int nonExistentPort = 54321; // hope this doesn't exist!
    Tunnel tunnel = Tunnel.build("localhost", nonExistentPort, "localhost", proxyServer.getServerSocketPort());
    try {// w  w w .  java2s  .  c  o m
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.configureBlocking(true);
        client.connect(new InetSocketAddress("localhost", tunnelPort));
        // Might have to write multiple times before connection error propagates back from proxy through tunnel to client
        for (int i = 0; i < 5; i++) {
            client.write(ByteBuffer.wrap("Knock\n".getBytes()));
            Thread.sleep(100);
        }
        String response1 = readFromSocket(client);
        LOG.info(response1);

        client.close();

    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
        assertEquals(proxyServer.getNumConnects(), 1);
    }
}

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

@Test(enabled = false, expectedExceptions = IOException.class)
public void testTunnelWhereProxyConnectionToServerFailsWithWriteFirstClient()
        throws IOException, InterruptedException {
    MockServer proxyServer = startConnectProxyServer();
    final int nonExistentPort = 54321; // hope this doesn't exist!
    Tunnel tunnel = Tunnel.build("localhost", nonExistentPort, "localhost", proxyServer.getServerSocketPort());
    try {/*from  ww w .  j a  v  a  2 s  . c  om*/
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.configureBlocking(true);
        client.connect(new InetSocketAddress("localhost", tunnelPort));
        // Might have to write multiple times before connection error propagates back from proxy through tunnel to client
        for (int i = 0; i < 5; i++) {
            client.write(ByteBuffer.wrap("Knock\n".getBytes()));
            Thread.sleep(100);
        }
        String response1 = readFromSocket(client);
        LOG.info(response1);

        client.close();

    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
        assertEquals(proxyServer.getNumConnects(), 1);
    }
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(timeOut = 15000)
public void testTunnelThreadDeadAfterClose() throws IOException, InterruptedException {
    MockServer proxyServer = startConnectProxyServer();
    Tunnel tunnel = Tunnel.build("localhost", talkFirstEchoServer.getServerSocketPort(), "localhost",
            proxyServer.getServerSocketPort());

    try {/*  www.j  av a2 s .c o m*/
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        String response0 = readFromSocket(client);
        LOG.info(response0);

        // write a lot of data to increase chance of response after close
        for (int i = 0; i < 1000; i++) {
            client.write(ByteBuffer.wrap("Knock\n".getBytes()));
        }

        // don't wait for response
        client.close();

        assertEquals(response0, "Hello\n");
        assertEquals(proxyServer.getNumConnects(), 1);
    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
    }
}

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

@Test(enabled = false, timeOut = 15000)
public void testTunnelThreadDeadAfterClose() throws IOException, InterruptedException {
    MockServer proxyServer = startConnectProxyServer();
    Tunnel tunnel = Tunnel.build("localhost", talkFirstEchoServer.getServerSocketPort(), "localhost",
            proxyServer.getServerSocketPort());

    try {/*from   w w  w .java2 s . c om*/
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        String response0 = readFromSocket(client);
        LOG.info(response0);

        // write a lot of data to increase chance of response after close
        for (int i = 0; i < 1000; i++) {
            client.write(ByteBuffer.wrap("Knock\n".getBytes()));
        }

        // don't wait for response
        client.close();

        assertEquals(response0, "Hello\n");
        assertEquals(proxyServer.getNumConnects(), 1);
    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
    }
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Lecture du fichier et envoi sur la socket.
 *
 * @param resultat/*from   w w  w .  j av  a  2  s .  c  o  m*/
 *            resultat
 * @param fileForTestSize
 *            fileForTestSize
 * @param channel
 *            channel
 * @param bufFileForTestRead
 *            bufFileForTestRead
 * @throws IOException
 *             IOException
 */
protected void readAndSendFile(final StringBuilder resultat, final long fileForTestSize,
        final SocketChannel channel, final MappedByteBuffer bufFileForTestRead) throws IOException {

    // Envoi de la commande
    final ByteBuffer writeReadBuffer = ByteBuffer.allocate(BUFFER_SIZE);
    writeReadBuffer.put(ClamAVCheckService.COMMANDE.getBytes(UTF_8));
    writeReadBuffer.put(this.intToByteArray((int) fileForTestSize));
    writeReadBuffer.flip();
    channel.write(writeReadBuffer);

    // Envoi du fichier

    long size = fileForTestSize;
    // envoi du fichier
    while (size > 0) {
        size -= channel.write(bufFileForTestRead);
    }
    final ByteBuffer writeBuffer = ByteBuffer.allocate(4);
    writeBuffer.put(new byte[] { 0, 0, 0, 0 });
    writeBuffer.flip();
    channel.write(writeBuffer);

    // lecture de la rponse
    ByteBuffer readBuffer;
    readBuffer = ByteBuffer.allocate(BUFFER_SIZE);
    // lecture de la rponse
    readBuffer.clear();
    boolean readLine = false;
    while (!readLine) {
        final int numReaden = channel.read(readBuffer);
        if (numReaden > 0) {
            readLine = readBuffer.get(numReaden - 1) == '\n';
            resultat.append(new String(readBuffer.array(), 0, numReaden, UTF_8));
            readBuffer.clear();
        } else {
            if (numReaden == -1) {
                readLine = true;
                readBuffer.clear();
            }
        }
    }
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void sendGarbageTest() throws IOException {

    InetSocketAddress socketAddress = new InetSocketAddress(PORT);
    SocketChannel channel = SocketChannel.open(socketAddress);
    channel.write(ByteBuffer.wrap(new byte[] { 1, 1, 1, 1 } // garbage
    ));//from ww  w. j a va 2  s  .  c  o  m
    channel.close();
}

From source file:Proxy.java

/**
 * Read all data from <code>from</code> and write it to <code>to</code>.
 * Returns false if channel was closed//from ww w  .  j  a  va2s  .c  o  m
 */
boolean relay(SocketChannel from, SocketChannel to, ByteBuffer buf) throws Exception {
    int num;
    StringBuilder sb;

    buf.clear();
    while (true) {
        num = from.read(buf);
        if (num < 0)
            return false;
        else if (num == 0)
            return true;
        buf.flip();
        if (verbose) {
            log(printRelayedData(toString(from), toString(to), buf.remaining()));
        }
        if (debug) {
            sb = new StringBuilder();
            sb.append(new String(buf.array()).trim());
            sb.append('\n');
            log(sb.toString());
        }
        to.write(buf);
        buf.flip();
    }
}