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.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 ww  w .  j  a v  a2 s.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:HttpDownloadManager.java

void handleError(DownloadImpl download, SocketChannel channel, SelectionKey key, Throwable throwable) {
    download.status = Status.ERROR;//from  www  .  j a va 2 s . com
    try {
        if (channel != null)
            channel.close();
    } catch (IOException e) {
    }
    if (key != null)
        key.cancel();
    log.log(Level.WARNING, "Error connecting to or downloading from " + download.host + ":" + download.port,
            throwable);
    if (download.listener != null)
        download.listener.error(download, throwable);
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnection.java

/**
 * Closes the underlying TCP connection if no more {@link TransferEnvelope} objects are in the transmission queue.
 * <p>//  w w w  . jav a 2s  . c o m
 * This method should only be called by the {@link OutgoingConnectionThread} object.
 * 
 * @throws IOException
 */
public void closeConnection() throws IOException {

    synchronized (this.queuedEnvelopes) {

        if (!this.queuedEnvelopes.isEmpty()) {
            return;
        }

        if (this.selectionKey != null) {

            final SocketChannel socketChannel = (SocketChannel) this.selectionKey.channel();
            socketChannel.close();
            this.selectionKey.cancel();
            this.selectionKey = null;
        }

        this.isConnected = false;
        this.isSubscribedToWriteEvent = false;
    }
}

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

private void get(String path, SocketAddress address) {
    try {// w w  w .  ja v  a2s  . c  o  m
        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 get(String path, SocketAddress address) {
    try {/*from  ww w. java 2 s  .com*/
        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.io.net.http.PostAndGetTests.java

private void post(String path, String data, SocketAddress address) {
    try {//w w w .  j a  v  a 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(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.io.netty.http.PostAndGetTests.java

private void post(String path, String data, SocketAddress address) {
    try {//from  w  w w  .  j  a  va  2s .  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.ipc.netty.http.client.PostAndGetTests.java

private void get(String path, SocketAddress address) {
    try {/*  w  ww . j ava 2 s.c o  m*/
        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 {/* www . j  a v a 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());
        Loggers.getLogger(PostAndGetTests.class).info("post: << " + "Response: %s", response);
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:InterruptibleSocketTest.java

/**
 * Connects to the test server, using interruptible I/O
 *//*w ww  .  jav  a2 s . c om*/
public void connectInterruptibly() throws IOException {
    messages.append("Interruptible:\n");
    SocketChannel channel = SocketChannel.open(new InetSocketAddress("localhost", 8189));
    try {
        in = new Scanner(channel);
        while (!Thread.currentThread().isInterrupted()) {
            messages.append("Reading ");
            if (in.hasNextLine()) {
                String line = in.nextLine();
                messages.append(line);
                messages.append("\n");
            }
        }
    } finally {
        channel.close();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                messages.append("Channel closed\n");
                interruptibleButton.setEnabled(true);
                blockingButton.setEnabled(true);
            }
        });
    }
}