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.galaxy.netty.http.HttpStaticFileServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//w  ww  . j a va2 s.c  o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpStaticFileServerInitializer());

        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.gdut.Netty_testing.dongjun.server.ElectricControlServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from w  w  w  . jav a2 s  . 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).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ElectricControlServerInitializer(sslCtx));

        b.bind(PORT).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}

From source file:com.gdut.Netty_testing.time_server.server.TimeServer.java

License:Apache License

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

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public 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), new TimeEncoder(),
                                new TimeServerHandler());
                        // new TimeEncoder(),
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        f.addListener(new GenericFutureListener<Future<? super Void>>() {

            public void operationComplete(Future<? super Void> future) throws Exception {
                // TODO Auto-generated method stub
                System.out.println("success " + future.isSuccess());
            }
        });

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.gemstone.gemfire.redis.GemFireRedisServer.java

License:Apache License

/**
 * Helper method to start the server listening for connections. The
 * server is bound to the port specified by {@link GemFireRedisServer#serverPort}
 * /*ww w .  j a va2s. com*/
 * @throws IOException
 * @throws InterruptedException
 */
private void startRedisServer() throws IOException, InterruptedException {
    ThreadFactory selectorThreadFactory = new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GemFireRedisServer-SelectorThread-" + counter.incrementAndGet());
            t.setDaemon(true);
            return t;
        }

    };

    ThreadFactory workerThreadFactory = new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("GemFireRedisServer-WorkerThread-" + counter.incrementAndGet());
            return t;
        }

    };

    bossGroup = null;
    workerGroup = null;
    Class<? extends ServerChannel> socketClass = null;
    if (singleThreadPerConnection) {
        bossGroup = new OioEventLoopGroup(Integer.MAX_VALUE, selectorThreadFactory);
        workerGroup = new OioEventLoopGroup(Integer.MAX_VALUE, workerThreadFactory);
        socketClass = OioServerSocketChannel.class;
    } else {
        bossGroup = new NioEventLoopGroup(this.numSelectorThreads, selectorThreadFactory);
        workerGroup = new NioEventLoopGroup(this.numWorkerThreads, workerThreadFactory);
        socketClass = NioServerSocketChannel.class;
    }
    InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem();
    String pwd = system.getConfig().getRedisPassword();
    final byte[] pwdB = Coder.stringToBytes(pwd);
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(socketClass).childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (logger.fineEnabled())
                logger.fine("GemFireRedisServer-Connection established with " + ch.remoteAddress());
            ChannelPipeline p = ch.pipeline();
            p.addLast(ByteToCommandDecoder.class.getSimpleName(), new ByteToCommandDecoder());
            p.addLast(ExecutionHandlerContext.class.getSimpleName(),
                    new ExecutionHandlerContext(ch, cache, regionCache, GemFireRedisServer.this, pwdB));
        }
    }).option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_RCVBUF, getBufferSize())
            .childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, GemFireRedisServer.connectTimeoutMillis)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // Bind and start to accept incoming connections.
    ChannelFuture f = b.bind(new InetSocketAddress(getBindAddress(), serverPort)).sync();
    if (this.logger.infoEnabled()) {
        String logMessage = "GemFireRedisServer started {" + getBindAddress() + ":" + serverPort
                + "}, Selector threads: " + this.numSelectorThreads;
        if (this.singleThreadPerConnection)
            logMessage += ", One worker thread per connection";
        else
            logMessage += ", Worker threads: " + this.numWorkerThreads;
        this.logger.info(logMessage);
    }
    this.serverChannel = f.channel();
}

From source file:com.github.ambry.rest.NettyServer.java

License:Open Source License

@Override
public void start() throws InstantiationException {
    long startupBeginTime = System.currentTimeMillis();
    try {/*  www.  j av  a2  s.  c  om*/
        logger.trace("Starting NettyServer deployment");
        ServerBootstrap b = new ServerBootstrap();
        // Netty creates a new instance of every class in the pipeline for every connection
        // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances.
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, nettyConfig.nettyServerSoBacklog)
                .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(channelInitializer);
        b.bind(nettyConfig.nettyServerPort).sync();
        logger.info("NettyServer now listening on port {}", nettyConfig.nettyServerPort);
    } catch (InterruptedException e) {
        logger.error("NettyServer start await was interrupted", e);
        nettyMetrics.nettyServerStartError.inc();
        throw new InstantiationException(
                "Netty server bind to port [" + nettyConfig.nettyServerPort + "] was interrupted");
    } finally {
        long startupTime = System.currentTimeMillis() - startupBeginTime;
        logger.info("NettyServer start took {} ms", startupTime);
        nettyMetrics.nettyServerStartTimeInMs.update(startupTime);
    }
}

From source file:com.github.gregwhitaker.requestreply.Server.java

License:Apache License

/**
 * Starts the server.//  w w  w . ja  va  2s  .  c om
 *
 * @throws Exception
 */
private void start() throws Exception {
    ServerBootstrap server = new ServerBootstrap();
    server.group(new NioEventLoopGroup(1), new NioEventLoopGroup(4)).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ReactiveSocketChannelInitializer());

    server.bind(bindAddress).sync();
}

From source file:com.github.herong.rpc.netty.protobuf.demo1.ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w ww . j  a  v  a2  s.c  o m
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(AddressBookProtos.AddressBook.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new ProtobufServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.herong.rpc.netty.protobuf.demo2.Demo2ProtobufServer.java

License:Apache License

public void run() throws Exception {
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w  w  w. jav a  2 s.com*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                // 
                                .addLast("frameDecoder", new ProtobufVarint32FrameDecoder())
                                // 
                                .addLast("protobufDecoder",
                                        new ProtobufDecoder(Message.DTO.getDefaultInstance()))
                                // 
                                .addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender())
                                .addLast("protobufEncoder", new ProtobufEncoder())
                                // 
                                .addLast("handler", new Demo2ProtobufServerHandler());
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(port).sync();

        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.github.liyp.netty.App.java

License:Apache License

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

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {/*ww  w.  j  a va  2s.  c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ReplayingDecoder() {
                            @Override
                            protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
                                    throws Exception {
                                short magicHeader = in.readShort();
                                logger.debug("Receive magic header: {}.", magicHeader);
                                if (magicHeader != HEADER) {
                                    logger.error("Receive illegal magic header: {}, close channel: {}.",
                                            magicHeader, ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                short dataLen = in.readShort();
                                logger.debug("Receive message data length: {}.", dataLen);
                                if (dataLen < 0) {
                                    logger.error("Data length is negative, close channel: {}.",
                                            ctx.channel().remoteAddress());
                                    ctx.close();
                                }

                                ByteBuf payload = in.readBytes(dataLen);
                                String cloudMsg = payload.toString(CharsetUtil.UTF_8);
                                logger.debug("Receive data: {}.", cloudMsg);
                                out.add(cloudMsg);
                            }
                        }).addLast(new MessageToByteEncoder<String>() {
                            @Override
                            protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out)
                                    throws Exception {
                                out.writeBytes(msg.getBytes());
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("start receive msg...");
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                logger.info("receive msg: {}", msg);
                                logger.info("echo msg");
                                ctx.writeAndFlush(msg);
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}

From source file:com.github.liyp.netty.HandlerChainApp.java

License:Apache License

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

    EventLoopGroup boss = new NioEventLoopGroup();
    EventLoopGroup worker = new NioEventLoopGroup();

    try {/*from w  w  w  .  j  a v  a  2  s.co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss, worker).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("1");
                                ctx.fireChannelActive();
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("2");
                                ctx.fireChannelActive();
                            }
                        }).addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                logger.info("3");
                                ctx.fireChannelActive();
                            }
                        });
                    }
                }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
        ChannelFuture f = b.bind(PORT).sync();
        logger.info("9999");
        f.channel().closeFuture().sync();
    } finally {
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}