Example usage for io.netty.channel.socket ServerSocketChannel localAddress

List of usage examples for io.netty.channel.socket ServerSocketChannel localAddress

Introduction

In this page you can find the example usage for io.netty.channel.socket ServerSocketChannel localAddress.

Prototype

@Override
    InetSocketAddress localAddress();

Source Link

Usage

From source file:com.addthis.meshy.MeshyServer.java

License:Apache License

public MeshyServer(final int port, final File rootDir, @Nullable String[] netif, final MeshyServerGroup group)
        throws IOException {
    super();/*from w ww  . j  a  v  a  2s . c  o m*/
    this.group = group;
    this.rootDir = rootDir;
    this.filesystems = loadFileSystems(rootDir);
    this.serverPeers = new AtomicInteger(0);
    bossGroup = new NioEventLoopGroup(1);
    ServerBootstrap bootstrap = new ServerBootstrap()
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .option(ChannelOption.SO_REUSEADDR, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, HIGH_WATERMARK)
            .childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, LOW_WATERMARK)
            .channel(NioServerSocketChannel.class).group(bossGroup, workerGroup)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ChannelState(MeshyServer.this, ch));
                }
            });
    /* bind to one or more interfaces, if supplied, otherwise all */
    if ((netif == null) || (netif.length == 0)) {
        ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap.bind(new InetSocketAddress(port))
                .syncUninterruptibly().channel();
        serverLocal = serverChannel.localAddress();
    } else {
        InetSocketAddress primaryServerLocal = null;
        for (String net : netif) {
            NetworkInterface nicif = NetworkInterface.getByName(net);
            if (nicif == null) {
                log.warn("missing speficied NIC: {}", net);
                continue;
            }
            for (InterfaceAddress addr : nicif.getInterfaceAddresses()) {
                InetAddress inAddr = addr.getAddress();
                if (inAddr.getAddress().length != 4) {
                    log.trace("skip non-ipV4 address: {}", inAddr);
                    continue;
                }
                ServerSocketChannel serverChannel = (ServerSocketChannel) bootstrap
                        .bind(new InetSocketAddress(inAddr, port)).syncUninterruptibly().channel();
                if (primaryServerLocal != null) {
                    log.info("server [{}-*] binding to extra address: {}", super.getUUID(), primaryServerLocal);
                }
                primaryServerLocal = serverChannel.localAddress();
            }
        }
        if (primaryServerLocal == null) {
            throw new IllegalArgumentException("no valid interface / port specified");
        }
        serverLocal = primaryServerLocal;
    }
    this.serverNetIf = NetworkInterface.getByInetAddress(serverLocal.getAddress());
    this.serverPort = serverLocal.getPort();
    if (serverNetIf != null) {
        serverUuid = super.getUUID() + "-" + serverPort + "-" + serverNetIf.getName();
    } else {
        serverUuid = super.getUUID() + "-" + serverPort;
    }
    log.info("server [{}] on {} @ {}", getUUID(), serverLocal, rootDir);
    closeFuture = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
    workerGroup.terminationFuture().addListener((Future<Object> workerFuture) -> {
        bossGroup.terminationFuture().addListener((Future<Object> bossFuture) -> {
            if (!workerFuture.isSuccess()) {
                closeFuture.tryFailure(workerFuture.cause());
            } else if (!bossFuture.isSuccess()) {
                closeFuture.tryFailure(bossFuture.cause());
            } else {
                closeFuture.trySuccess(null);
            }
        });
    });
    addMessageFileSystemPaths();
    group.join(this);
    if (autoMesh) {
        startAutoMesh(serverPort, autoMeshTimeout);
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java

License:Open Source License

@Test(expected = ConnectException.class, timeout = 30000)
public void timeoutShouldWork_connect() throws Exception {
    ServerSocketChannel server = startServer(new ChannelHandlerAdapter() {
    });/*from   www  .j  a  v a2s .co  m*/
    int serverPort = server.localAddress().getPort();
    closeServerChannel(server);

    Credentials credentials = newCredentials();
    HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 5, credentials);
    blobStore.get("key", new ByteArrayOutputStream());
    fail("Exception expected");
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java

License:Open Source License

@Test(expected = ReadTimeoutException.class, timeout = 30000)
public void timeoutShouldWork_read() throws Exception {
    ServerSocketChannel server = null;
    try {//from w  w w  .j  av a  2  s.  c o  m
        server = startServer(new SimpleChannelInboundHandler<FullHttpRequest>() {
            @Override
            protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                    FullHttpRequest fullHttpRequest) {
                // Don't respond and force a client timeout.
            }
        });
        int serverPort = server.localAddress().getPort();

        Credentials credentials = newCredentials();
        HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 5, credentials);
        blobStore.get("key", new ByteArrayOutputStream());
        fail("Exception expected");
    } finally {
        closeServerChannel(server);
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java

License:Open Source License

private void expiredAuthTokensShouldBeRetried_get(ErrorType errorType) throws Exception {
    ServerSocketChannel server = null;
    try {/*from  w w  w. j a v  a 2s  . c om*/
        server = startServer(new NotAuthorizedHandler(errorType));
        int serverPort = server.localAddress().getPort();

        Credentials credentials = newCredentials();
        HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 30, credentials);
        ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream());
        blobStore.get("key", out);
        assertThat(out.toString(Charsets.US_ASCII.name())).isEqualTo("File Contents");
        verify(credentials, times(1)).refresh();
        verify(credentials, times(2)).getRequestMetadata(any(URI.class));
        verify(credentials, times(2)).hasRequestMetadata();
        // The caller is responsible to the close the stream.
        verify(out, never()).close();
        verifyNoMoreInteractions(credentials);
    } finally {
        closeServerChannel(server);
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java

License:Open Source License

private void expiredAuthTokensShouldBeRetried_put(ErrorType errorType) throws Exception {
    ServerSocketChannel server = null;
    try {//from   w ww  .  j  ava 2s.  c o m
        server = startServer(new NotAuthorizedHandler(errorType));
        int serverPort = server.localAddress().getPort();

        Credentials credentials = newCredentials();
        HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 30, credentials);
        byte[] data = "File Contents".getBytes(Charsets.US_ASCII);
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        blobStore.put("key", data.length, in);
        verify(credentials, times(1)).refresh();
        verify(credentials, times(2)).getRequestMetadata(any(URI.class));
        verify(credentials, times(2)).hasRequestMetadata();
        verifyNoMoreInteractions(credentials);
    } finally {
        closeServerChannel(server);
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java

License:Open Source License

private void errorCodeThatShouldNotBeRetried_get(ErrorType errorType) throws InterruptedException {
    ServerSocketChannel server = null;
    try {//w w  w  . ja  v a2s .  c om
        server = startServer(new NotAuthorizedHandler(errorType));
        int serverPort = server.localAddress().getPort();

        Credentials credentials = newCredentials();
        HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 30, credentials);
        blobStore.get("key", new ByteArrayOutputStream());
        fail("Exception expected.");
    } catch (Exception e) {
        assertThat(e).isInstanceOf(HttpException.class);
        assertThat(((HttpException) e).response().status()).isEqualTo(HttpResponseStatus.UNAUTHORIZED);
    } finally {
        closeServerChannel(server);
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java

License:Open Source License

private void errorCodeThatShouldNotBeRetried_put(ErrorType errorType) throws InterruptedException {
    ServerSocketChannel server = null;
    try {/*from   w ww  .j  av  a 2s. co  m*/
        server = startServer(new NotAuthorizedHandler(errorType));
        int serverPort = server.localAddress().getPort();

        Credentials credentials = newCredentials();
        HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 30, credentials);
        blobStore.put("key", 1, new ByteArrayInputStream(new byte[] { 0 }));
        fail("Exception expected.");
    } catch (Exception e) {
        assertThat(e).isInstanceOf(HttpException.class);
        assertThat(((HttpException) e).response().status()).isEqualTo(HttpResponseStatus.UNAUTHORIZED);
    } finally {
        closeServerChannel(server);
    }
}

From source file:com.turn.ttorrent.client.io.PeerServer.java

License:Apache License

@Nonnull
public InetSocketAddress getLocalAddress() {
    ServerSocketChannel channel = (ServerSocketChannel) future.channel();
    return channel.localAddress();
}