Example usage for java.nio.channels SocketChannel close

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

Introduction

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

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:org.cloudata.core.commitlog.FileTransferThread.java

public void run() {
    SocketChannel socketChannel = null;

    try {/*from w ww  .  j  av  a 2s.c  o m*/
        if (selector.select(5000) > 0) {
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();

            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                if (key.isValid() && key.isAcceptable()) {
                    socketChannel = ssc.accept();

                    transfer(channelList, socketChannel);
                }

                iter.remove();
            }
        } else {
            LOG.warn("No responses from client asking to transfter file for 5 sec");
        }
    } catch (IOException e) {
        LOG.warn("transfering file is fail", e);
    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.socket().close();
                socketChannel.close();
            } catch (IOException e) { /* ignored */
            }
        }
    }

    LOG.debug("File transfer thread is done");
}

From source file:com.alexkli.jhb.Worker.java

@Override
public void run() {
    try {/*from   ww  w .j a va  2  s . c  o  m*/
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:morphy.service.SocketConnectionService.java

protected synchronized String readMessage(SocketChannel channel) {
    try {/*ww  w  . j  a va2 s .co  m*/
        ByteBuffer buffer = ByteBuffer.allocate(maxCommunicationSizeBytes);
        int charsRead = -1;
        try {
            charsRead = channel.read(buffer);
        } catch (IOException cce) {
            if (channel.isOpen()) {
                channel.close();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Closed channel " + channel);
                }
            }
        }
        if (charsRead == -1) {
            return null;
        } else if (charsRead > 0) {
            buffer.flip();

            Charset charset = Charset.forName(Morphy.getInstance().getMorphyPreferences()
                    .getString(PreferenceKeys.SocketConnectionServiceCharEncoding));

            SocketChannelUserSession socketChannelUserSession = socketToSession.get(channel.socket());

            byte[] bytes = buffer.array();
            buffer.position(0);

            System.out.println("IN: " + new String(bytes).trim());
            if (looksLikeTimesealInit(bytes)) {
                if (socketChannelUserSession.usingTimeseal == false) {
                    // First time?
                    socketChannelUserSession.usingTimeseal = true;
                    return MSG_TIMESEAL_OK;
                }
            }

            if (socketChannelUserSession.usingTimeseal) {
                /*
                 * Clients may pass multiple Timeseal-encoded messages at once.
                 * We need to parse each separated message to Timeseal decoder as necessary. 
                 */

                byte[] bytesToDecode = Arrays.copyOfRange(bytes, 0, charsRead - 1 /* \n or 10 */);
                byte[][] splitBytes = TimesealCoder.splitBytes(bytesToDecode, (byte) 10);

                buffer = ByteBuffer.allocate(bytesToDecode.length);
                buffer.position(0);
                for (int i = 0; i < splitBytes.length; i++) {
                    byte[] splitBytesToDecode = splitBytes[i];
                    TimesealParseResult parseResult = timesealCoder.decode(splitBytesToDecode);
                    if (parseResult != null) {
                        System.out.println(parseResult.getTimestamp());
                        parseResult.setMessage(parseResult.getMessage() + "\n");
                        System.out.println(parseResult.getMessage());

                        buffer.put(parseResult.getMessage().getBytes(charset));
                    }
                }
                //buffer.position(0);
                buffer.flip();
            }

            CharsetDecoder decoder = charset.newDecoder();
            CharBuffer charBuffer = decoder.decode(buffer);
            String message = charBuffer.toString();
            return message;
            //System.out.println(message);
            //return "";
        } else {
            return "";
        }
    } catch (Throwable t) {
        if (LOG.isErrorEnabled())
            LOG.error("Error reading SocketChannel " + channel.socket().getLocalAddress(), t);
        return null;
    }
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(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 {/*from   ww  w . ja  va 2  s  .c om*/
        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: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 {/*  w w w  . j ava 2  s .c  om*/
        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

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

    try {//  www.jav  a  2  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 {/* www. j a v  a  2  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: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);//from  w  w  w .  j  a v  a2  s  . com

    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:net.socket.nio.TimeClientHandle.java

private void handleInput(SelectionKey key) throws IOException {

    if (key.isValid()) {
        // ??/* w ww  .j  a  va  2  s . c  om*/
        SocketChannel sc = (SocketChannel) key.channel();
        if (key.isConnectable()) {
            if (sc.finishConnect()) {
                sc.register(selector, SelectionKey.OP_READ);
                doWrite(sc);
            } else {
                System.exit(1);// 
            }
        }
        if (key.isReadable()) {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                String body = new String(bytes, "UTF-8");
                System.out.println("Now is : " + body);
                this.stop = true;
            } else if (readBytes < 0) {
                // 
                key.cancel();
                sc.close();
            } else {
                ; // 0
            }
        }
    }

}

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

/**
 * Accept an icoming connection/* w  ww.  j  a va  2  s  . co m*/
 * 
 * @throws IOException
 */
private void processAccept(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

    ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
    SocketChannel channel = ssc.accept();

    if (channel == null)
        return;

    if (channel.isOpen() && accept(channel.socket().getInetAddress())) {

        channel.configureBlocking(false);

        DaapConnection connection = new DaapConnectionNIO(this, channel);

        SelectionKey key = channel.register(selector, SelectionKey.OP_READ, connection);

    } else {
        try {
            channel.close();
        } catch (IOException err) {
            LOG.error("SocketChannel.close()", err);
        }
    }
}