Example usage for java.nio.channels ServerSocketChannel getLocalAddress

List of usage examples for java.nio.channels ServerSocketChannel getLocalAddress

Introduction

In this page you can find the example usage for java.nio.channels ServerSocketChannel getLocalAddress.

Prototype

@Override
public abstract SocketAddress getLocalAddress() throws IOException;

Source Link

Document

If there is a security manager set, its checkConnect method is called with the local address and -1 as its arguments to see if the operation is allowed.

Usage

From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java

/**
 * //from  w w  w .j  a  v  a 2s . c  o  m
 */
@Override
void init() throws IOException {
    ServerSocketChannel channel = (ServerSocketChannel) this.rootChannel;
    channel.configureBlocking(false);
    channel.socket().bind(this.address);
    channel.register(this.selector, SelectionKey.OP_ACCEPT);

    if (logger.isInfoEnabled()) {
        logger.info("Bound to " + channel.getLocalAddress());
    }
}

From source file:org.cryptomator.ui.util.SingleInstanceManager.java

/**
 * Creates a server socket on a free port and saves the port in
 * {@link Preferences#userNodeForPackage(Class)} for {@link Main} under the
 * given applicationKey.//from  w  w w  .  j  ava2s . c o m
 * 
 * @param applicationKey
 *            key used to save the port and identify upon connection.
 * @param exec
 *            the task which is submitted is interruptable.
 * @return
 * @throws IOException
 */
public static LocalInstance startLocalInstance(String applicationKey, ExecutorService exec) throws IOException {
    final ServerSocketChannel channel = ServerSocketChannel.open();
    channel.configureBlocking(false);
    channel.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));

    final int port = ((InetSocketAddress) channel.getLocalAddress()).getPort();
    Preferences.userNodeForPackage(Main.class).putInt(applicationKey, port);
    LOG.info("InstanceManager bound to port {}", port);

    Selector selector = Selector.open();
    channel.register(selector, SelectionKey.OP_ACCEPT);

    LocalInstance instance = new LocalInstance(applicationKey, channel, selector);

    exec.submit(() -> {
        try {
            instance.port = ((InetSocketAddress) channel.getLocalAddress()).getPort();
        } catch (IOException e) {

        }
        instance.selectionLoop();
    });

    return instance;
}

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);//from   ww w . jav  a  2  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) {

        }
    });
    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: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 ww  .  j  av  a  2 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
                }
            } 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: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 w w  .  j a  va  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) {

        }
    });

    // 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));
}