Example usage for io.netty.bootstrap ServerBootstrap childHandler

List of usage examples for io.netty.bootstrap ServerBootstrap childHandler

Introduction

In this page you can find the example usage for io.netty.bootstrap ServerBootstrap childHandler.

Prototype

ChannelHandler childHandler

To view the source code for io.netty.bootstrap ServerBootstrap childHandler.

Click Source Link

Usage

From source file:com.shiyq.netty.http.HttpUploadServer.java

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*w  w  w  .  j  a  va  2 s  .  co  m*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler((ChannelHandler) new HttpUploadServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.spotify.ffwd.debug.NettyDebugServer.java

License:Apache License

public AsyncFuture<Void> start() {
    final ResolvableFuture<Void> future = async.future();

    final ServerBootstrap s = new ServerBootstrap();

    s.channel(NioServerSocketChannel.class);
    s.group(boss, worker);/* ww  w. j  a  va  2  s  .c  om*/

    s.childHandler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            connected.add(ch);
            log.info("Connected {}", ch);

            ch.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    connected.remove(ch);
                    log.info("Disconnected {}", ch);
                }
            });
        }
    });

    s.bind(localAddress).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture f) throws Exception {
            if (!f.isSuccess()) {
                future.fail(f.cause());
                return;
            }

            log.info("Bound to {}", localAddress);

            if (!server.compareAndSet(null, f.channel())) {
                f.channel().close();
                future.fail(new IllegalStateException("server already started"));
                return;
            }

            future.resolve(null);
        }
    });

    return future;
}

From source file:com.spotify.ffwd.protocol.ProtocolServersImpl.java

License:Apache License

private AsyncFuture<ProtocolConnection> bindTCP(final Logger log, final Protocol protocol,
        ProtocolServer server, RetryPolicy policy) {
    final ServerBootstrap b = new ServerBootstrap();

    b.group(boss, worker);//  www  .  j av a2s .c  o  m
    b.channel(NioServerSocketChannel.class);
    b.childHandler(server.initializer());

    b.option(ChannelOption.SO_BACKLOG, 128);

    if (protocol.getReceiveBufferSize() != null) {
        b.childOption(ChannelOption.SO_RCVBUF, protocol.getReceiveBufferSize());
    }

    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    final String host = protocol.getAddress().getHostString();
    final int port = protocol.getAddress().getPort();

    final RetryingProtocolConnection connection = new RetryingProtocolConnection(async, timer, log, policy,
            new ProtocolChannelSetup() {
                @Override
                public ChannelFuture setup() {
                    return b.bind(host, port);
                }

                @Override
                public String toString() {
                    return String.format("bind tcp://%s:%d", host, port);
                }
            });

    return connection.getInitialFuture();
}

From source file:com.spotify.heroic.rpc.nativerpc.NativeRpcProtocolServer.java

License:Apache License

private AsyncFuture<Void> start() {
    final ServerBootstrap s = new ServerBootstrap();
    s.channel(NioServerSocketChannel.class);
    s.group(bossGroup, workerGroup);/*  w w w .j a  v a2s .  com*/
    s.childHandler(new NativeRpcServerSession(timer, mapper, container, maxFrameSize, encoding));

    final ChannelFuture bind = s.bind(address);

    bind.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture f) throws Exception {
            if (!f.isSuccess()) {
                bindFuture.fail(f.cause());
                return;
            }

            serverChannel.set(f.channel());
            final InetSocketAddress address = (InetSocketAddress) f.channel().localAddress();
            bindFuture.resolve(address);
        }
    });

    return bindFuture.directTransform(a -> null);
}

From source file:com.spotify.netty4.handler.codec.zmtp.EndToEndTest.java

License:Apache License

private Channel bind(final SocketAddress address, final ChannelHandler codec, final ChannelHandler handler) {
    final ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(new NioEventLoopGroup(1), new NioEventLoopGroup());
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
        @Override/*from  w  w w.jav a  2  s.c  o m*/
        protected void initChannel(final NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(codec, handler);
        }
    });
    return bootstrap.bind(address).awaitUninterruptibly().channel();
}

From source file:com.spotify.netty4.handler.codec.zmtp.ProtocolViolationTests.java

License:Apache License

@Before
public void setup() {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.channel(NioServerSocketChannel.class);
    bossGroup = new NioEventLoopGroup(1);
    group = new NioEventLoopGroup();
    serverBootstrap.group(bossGroup, group);
    serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
        @Override//from   w  ww .  ja  va 2s.  c  o  m
        protected void initChannel(final NioSocketChannel ch) throws Exception {
            ch.pipeline().addLast(
                    ZMTPCodec.builder().protocol(ZMTP20).socketType(ROUTER).localIdentity(identity).build(),
                    mockHandler);
        }
    });

    serverChannel = serverBootstrap.bind(new InetSocketAddress("localhost", 0)).awaitUninterruptibly()
            .channel();
    serverAddress = (InetSocketAddress) serverChannel.localAddress();
}

From source file:com.topsec.bdc.platform.api.test.http.upload.HttpUploadServer.java

License:Apache License

public static void main(String[] args) throws Exception {

    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* w w w  . ja v  a2s.  c  om*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.handler(new LoggingHandler(LogLevel.INFO));
        b.childHandler(new HttpUploadServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:"
                + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

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

License:Apache License

/**
 * Create and start a new listening service for our torrents, reporting
 * with our peer ID on the given address.
 *
 * <p>// w w  w . ja  v a 2s.c om
 * This binds to the first available port in the client port range
 * PORT_RANGE_START to PORT_RANGE_END.
 * </p>
 */
public void start() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(environment.getEventService());
    bootstrap.channel(environment.getEventLoopType().getServerChannelType());
    bootstrap.option(ChannelOption.SO_BACKLOG, 128);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.childHandler(new ChannelInitializer() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new PeerServerHandshakeHandler(torrents));
        }
    });
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    // bootstrap.childOption(ChannelOption.SO_TIMEOUT, (int) TimeUnit.MINUTES.toMillis(CLIENT_KEEP_ALIVE_MINUTES));
    // TODO: Derive from PieceHandler.DEFAULT_BLOCK_SIZE
    // bootstrap.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 1024 * 1024);
    // bootstrap.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
    SocketAddress address = environment.getLocalPeerListenAddress();
    if (address != null) {
        future = bootstrap.bind(address).sync();
    } else {
        BIND: {
            Exception x = new IOException("No available port for the BitTorrent client!");
            for (int i = PORT_RANGE_START; i <= PORT_RANGE_END; i++) {
                try {
                    future = bootstrap.bind(i).sync();
                    break BIND;
                } catch (InterruptedException e) {
                    throw e;
                } catch (Exception e) {
                    x = e;
                }
            }
            throw new IOException("Failed to find an address to bind in range [" + PORT_RANGE_START + ","
                    + PORT_RANGE_END + "]", x);
        }
    }
}

From source file:com.twocater.diamond.core.test.DiscardServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from  ww  w.  ja  va  2  s.com
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new DiscardServerHandler());
            }
        });
        b.option(ChannelOption.SO_BACKLOG, 128);
        b.childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture f = b.bind(port).sync();
        System.out.println("bind");
        f.channel().closeFuture().sync();
        System.out.println("close");
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}

From source file:com.yahoo.pulsar.broker.service.BrokerService.java

License:Apache License

public void start() throws Exception {
    this.producerNameGenerator = new DistributedIdGenerator(pulsar.getZkClient(), producerNameGeneratorPath,
            pulsar.getConfiguration().getClusterName());

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    bootstrap.group(acceptorGroup, workerGroup);
    bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
    bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR,
            new AdaptiveRecvByteBufAllocator(1024, 16 * 1024, 1 * 1024 * 1024));

    if (workerGroup instanceof EpollEventLoopGroup) {
        bootstrap.channel(EpollServerSocketChannel.class);
        bootstrap.childOption(EpollChannelOption.EPOLL_MODE, EpollMode.LEVEL_TRIGGERED);
    } else {/*from   w  w  w  .j ava 2s  .co m*/
        bootstrap.channel(NioServerSocketChannel.class);
    }

    ServiceConfiguration serviceConfig = pulsar.getConfiguration();

    bootstrap.childHandler(new PulsarChannelInitializer(this, serviceConfig, false));
    // Bind and start to accept incoming connections.
    bootstrap.bind(new InetSocketAddress(pulsar.getBindAddress(), port)).sync();
    log.info("Started Pulsar Broker service on port {}", port);

    if (serviceConfig.isTlsEnabled()) {
        ServerBootstrap tlsBootstrap = bootstrap.clone();
        tlsBootstrap.childHandler(new PulsarChannelInitializer(this, serviceConfig, true));
        tlsBootstrap.bind(new InetSocketAddress(pulsar.getBindAddress(), tlsPort)).sync();
        log.info("Started Pulsar Broker TLS service on port {}", tlsPort);
    }

    // start other housekeeping functions
    this.startStatsUpdater();
    this.startInactivityMonitor();
    this.startMessageExpiryMonitor();
    this.startBacklogQuotaChecker();
}