Example usage for io.netty.bootstrap ServerBootstrap group

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

Introduction

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

Prototype

public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) 

Source Link

Document

Set the EventLoopGroup for the parent (acceptor) and the child (client).

Usage

From source file:com.sohail.alam.http.server.SetupServer.java

License:Apache License

public void initialize() {
    final ServerBootstrap serverBootstrap = new ServerBootstrap();
    final EventLoopGroup boss = new NioEventLoopGroup();
    final EventLoopGroup worker = new NioEventLoopGroup();

    serverBootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_BACKLOG, ServerProperties.PROP.SO_BACKLOG)
            .childOption(ChannelOption.TCP_NODELAY, ServerProperties.PROP.TCP_NODELAY)
            .childOption(ChannelOption.SO_KEEPALIVE, ServerProperties.PROP.SO_KEEPALIVE)
            .childOption(ChannelOption.SO_REUSEADDR, ServerProperties.PROP.SO_REUSEADDR)
            .childHandler(new HttpChannelInitializer());

    try {/*from   w ww. j ava  2 s  .  c o m*/
        ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(ip, port)).sync();
        if (future.isSuccess()) {
            LoggerManager.LOGGER.info("Http Server Started Successfully @ {}:{}", ip, port);
        } else {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            LoggerManager.LOGGER.fatal("Http Server Start Failed. Can not bind to {}:{}", ip, port);
        }
    } catch (Exception e) {
        LoggerManager.LOGGER.fatal("Exception Caught while starting Http Server", e);
    }

}

From source file:com.sohu.jafka.http.HttpServer.java

License:Apache License

public void run() {
    // Configure the server.
    ///*from  w ww . ja  v  a 2s.c om*/

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerInitializer(this));

        Channel ch = b.bind(port).sync().channel();
        //System.err.println("Open your web browser and navigate to " + "http://127.0.0.1:" + port + '/');
        logger.info("Jafka HttpServer start at port {}", port);
        ch.closeFuture().sync();
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(ie.getMessage(), ie);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
    logger.warn("Jafka HttpServer run over");
}

From source file:com.splicemachine.stream.StreamListenerServer.java

License:Apache License

public void start() throws StandardException {
    ThreadFactory tf = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("StreamerListenerServer-boss-%s").build();
    this.bossGroup = new NioEventLoopGroup(4, tf);
    tf = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("StreamerListenerServer-worker-%s").build();
    this.workerGroup = new NioEventLoopGroup(4, tf);
    try {/*from  www  .ja  v a  2 s.  c o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new OpenHandler(this))
                .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync();

        this.serverChannel = f.channel();
        InetSocketAddress socketAddress = (InetSocketAddress) this.serverChannel.localAddress();
        String host = InetAddress.getLocalHost().getHostName();
        int port = socketAddress.getPort();

        this.hostAndPort = HostAndPort.fromParts(host, port);
        LOG.info("StreamListenerServer listening on " + hostAndPort);

    } catch (IOException e) {
        throw Exceptions.parseException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

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

    s.childHandler(new ChannelInitializer<Channel>() {
        @Override/*from  w ww.  j  a  v a  2  s  .c o  m*/
        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);
    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());
    }//from  www  .j  av a 2  s. c om

    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);
    s.childHandler(new NativeRpcServerSession(timer, mapper, container, maxFrameSize, encoding));

    final ChannelFuture bind = s.bind(address);

    bind.addListener(new ChannelFutureListener() {
        @Override/*from  w  w  w. j  a v a2  s  .c  o m*/
        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. j av a2  s.co 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   www . j a  v  a2 s .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.springapp.mvc.netty.example.spdy.server.SpdyServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .applicationProtocolConfig(/*from  ww w . j  av a2 s  .  c o  m*/
                    new ApplicationProtocolConfig(Protocol.NPN, SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
                            SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL,
                            SelectedProtocol.SPDY_3_1.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()))
            .build();

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new SpdyServerInitializer(sslCtx));

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

        System.err
                .println("Open your SPDY-enabled web browser and navigate to https://127.0.0.1:" + PORT + '/');
        System.err.println("If using Chrome browser, check your SPDY sessions at chrome://net-internals/#spdy");

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

From source file:com.srotya.linea.network.InternalTCPTransportServer.java

License:Apache License

public void init() throws Exception {
    final SslContext sslCtx;
    if (SSL) {//from w  ww.  j  av  a 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(1);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (sslCtx != null) {
                        p.addLast(sslCtx.newHandler(ch.alloc()));
                    }
                    p.addLast(new LoggingHandler(LogLevel.INFO));
                    p.addLast(new KryoObjectEncoder());
                    p.addLast(new KryoObjectDecoder());
                    p.addLast(new IWCHandler(null)); //TODO add router
                }

            }).bind(Inet4Address.getByName("localhost"), 9999).sync().channel().closeFuture().await();

}