Example usage for io.netty.bootstrap ServerBootstrap ServerBootstrap

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

Introduction

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

Prototype

public ServerBootstrap() 

Source Link

Usage

From source file:com.athena.peacock.controller.netty.PeacockServer.java

License:Open Source License

@Override
public void afterPropertiesSet() throws Exception {
    new Thread() {
        @Override/* w ww  .  j av  a  2 s.c o  m*/
        public void run() {
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                        .handler(new LoggingHandler(LogLevel.WARN)).childHandler(initializer);

                // Bind and start to accept incoming connections.
                channel = b.bind(port).sync().channel().closeFuture().sync().channel();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

From source file:com.avanza.astrix.netty.server.NettyRemotingServer.java

License:Apache License

public void start() {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, false).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w ww  . j  a va 2  s  . co m*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                            new NettyRemotingServerHandler(serviceActivator));
                }
            });

    // Bind and start to accept incoming connections. Binds to all interfaces
    // TODO: Allow specifying a bind port range. Attempt to bind to each port in range and use first successfully bound port
    ChannelFuture channel = b.bind(port);
    try {
        if (channel.await(2, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                port = InetSocketAddress.class.cast(channel.channel().localAddress()).getPort();
                log.info("NettyRemotingServer started listening on port={}", port);
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    throw new IllegalStateException("Failed to start netty remoting server. Can't bind to port: " + port);
}

From source file:com.baidu.jprotobuf.pbrpc.management.HttpServer.java

License:Apache License

public void start(int port) {

    serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//ww w.j  a va  2s.com
                public void initChannel(SocketChannel ch) throws Exception {
                    // server??httpResponse?HttpResponseEncoder?
                    ch.pipeline().addLast(new HttpResponseEncoder());
                    // serverhttpRequest?HttpRequestDecoder?
                    ch.pipeline().addLast(new HttpRequestDecoder());
                    ch.pipeline().addLast(new HttpServerInboundHandler(rpcServer));
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

    serverBootstrap.bind(port).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                // TODO notifyStarted();
            } else {
                // TODO notifyFailed(future.cause());
            }
        }
    });

    LOG.log(Level.INFO, "Http starting at port: " + port);
}

From source file:com.baidu.rigel.biplatform.ma.file.serv.FileServer.java

License:Open Source License

private static void startServer(String location, int port) {
    fileLocation = new FileLocation(location);
    service = new LocalFileOperationServiceImpl(fileLocation);
    EventLoopGroup bossGroup = new NioEventLoopGroup(10);
    EventLoopGroup workGroup = new NioEventLoopGroup(50);
    try {//from ww  w .  j  a v  a  2s .c o  m
        ServerBootstrap strap = new ServerBootstrap();
        strap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        // ??
                        channel.pipeline().addLast(new ObjectDecoder(ClassResolvers
                                .weakCachingConcurrentResolver(FileServer.class.getClassLoader())));
                        channel.pipeline().addLast(new ObjectEncoder());
                        //                        channel.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());
                        channel.pipeline().addLast(new FileServer());
                    }
                });
        ChannelFuture future = strap.bind(port).sync();
        LOGGER.info("start file server successfully");
        LOGGER.info("port : " + port);
        LOGGER.info("location : " + location);
        future.channel().closeFuture().sync();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        LOGGER.error("can not start file server with [port : {}] and fileLocation {{}}", port, location);
        printUsage();
        System.exit(-1);
    } finally {
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.node.service.IndexAndSearchServer.java

License:Open Source License

/**
 * startServer/*from   ww  w  .  j  a  v a 2  s.  com*/
 * 
 * @throws Exception
 */
protected void startServer() throws Exception {
    LOGGER.info("Index and Search server ready to start...");
    long curr = System.currentTimeMillis();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.option(ChannelOption.SO_BACKLOG, 1000000);
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            /*
             * (non-Javadoc)
             * 
             * @see
             * io.netty.channel.ChannelInitializer#initChannel(io.netty.
             * channel.Channel)
             */
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("encode", new ObjectEncoder());
                pipeline.addLast("decode",
                        new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
                pipeline.addLast(IndexServerHandler.getChannelHandler());
                pipeline.addLast(SearchServerHandler.getChannelHandler());
                pipeline.addLast(FileServerHandler.getChannelHandler());
            }

        });

        // ChannelFuture f = b.bind(IP, PORT).sync();
        // f.channel().closeFuture().sync();

        int currPort = NetworkUtils.getAvailablePort(this.node.getPort());

        ChannelFuture f = b.bind(IP, currPort).sync();

        if (currPort != this.node.getPort()) {
            this.node.setPort(currPort);
        }

        serverChannelFuture = f;
        LOGGER.info("Index and Search server started at Port:" + this.node.getPort());
        LOGGER.info("Index and Search server started in " + (System.currentTimeMillis() - curr) + "ms");
        this.isRunning = true;

        serverChannelFuture.channel().closeFuture().sync().channel();

    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.bala.learning.learning.netty.HttpServer.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  . com
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpServerInitializer(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.baoxue.netty.file.FileServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from w w w.  j ava2 s .c  om*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
                    /*
                     * (non-Javadoc)
                     * 
                     * @see
                     * io.netty.channel.ChannelInitializer#initChannel(io
                     * .netty.channel.Channel)
                     */
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8),
                                new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8),
                                new FileServerHandler());
                    }
                });
        ChannelFuture f = b.bind(port).sync();
        System.out.println("Start file server at port : " + port);
        f.channel().closeFuture().sync();
    } finally {
        // ?
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:com.barchart.http.server.HttpServer.java

License:BSD License

/**
 * Start the server with the configuration settings provided.
 *///  w w  w  . j av a2s .  com
public ChannelFuture listen() {

    if (config == null) {
        throw new IllegalStateException("Server has not been configured");
    }

    if (serverChannel != null) {
        throw new IllegalStateException("Server is already running.");
    }

    final ChannelFuture future = new ServerBootstrap() //
            .group(config.parentGroup(), config.childGroup()) //
            .channel(NioServerSocketChannel.class) //
            .localAddress(config.address()) //
            .childHandler(new HttpServerChannelInitializer()) //
            .option(ChannelOption.SO_REUSEADDR, true) //
            .option(ChannelOption.SO_SNDBUF, 262144) //
            .option(ChannelOption.SO_RCVBUF, 262144) //
            .bind();

    serverChannel = future.channel();

    return future;

}

From source file:com.barchart.netty.server.base.AbstractStatefulServer.java

License:BSD License

@Override
protected ServerBootstrap bootstrap() {

    final ServerBootstrap bootstrap = new ServerBootstrap() //
            .group(defaultGroup, childGroup) //
            .channel(channelType) //
            .childHandler(new ServerChannelInitializer()) //
            .option(ChannelOption.SO_REUSEADDR, true) //
            .option(ChannelOption.SO_SNDBUF, 262144) //
            .option(ChannelOption.SO_RCVBUF, 262144) //
            .childOption(ChannelOption.SO_SNDBUF, 262144) //
            .childOption(ChannelOption.SO_RCVBUF, 262144);

    if (bootstrapInit != null) {
        bootstrapInit.initBootstrap(bootstrap);
    }//  w  w  w.j a  v  a 2 s  .c  om

    return bootstrap;

}

From source file:com.base.research.socket.netty.Server.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*w ww  .  j  ava 2s  .  c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        // ch.pipeline().addLast(new TimeDecode());
                        ch.pipeline().addLast(new TestDecode2());
                        // ch.pipeline().addLast(new TestEncode());
                        ch.pipeline().addLast(new TestEncode2());
                        ch.pipeline().addLast(new ServerHandler());
                    }
                });

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

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to
        // gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}