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.alibaba.dubbo.remoting.transport.netty4.NettyServer.java

License:Apache License

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();

    bootstrap = new ServerBootstrap();

    bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("NettyServerBoss", true));
    workerGroup = new NioEventLoopGroup(
            getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),
            new DefaultThreadFactory("NettyServerWorker", true));

    final NettyServerHandler nettyServerHandler = new NettyServerHandler(getUrl(), this);
    channels = nettyServerHandler.getChannels();

    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)
            .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override//from   w ww.j a v  a  2 s .c  om
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);
                    ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                            .addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder())
                            .addLast("handler", nettyServerHandler);
                }
            });
    // bind
    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());
    channelFuture.syncUninterruptibly();
    channel = channelFuture.channel();

}

From source file:com.alibaba.rocketmq.remoting.netty.NettyRemotingServer.java

License:Apache License

public NettyRemotingServer(final NettyServerConfig nettyServerConfig,
        final ChannelEventListener channelEventListener) {
    super(nettyServerConfig.getServerOnewaySemaphoreValue(), nettyServerConfig.getServerAsyncSemaphoreValue());
    String name = SystemPropertyUtil.get("os.name").toLowerCase(Locale.UK).trim();
    isLinux = name.startsWith("linux");
    isLinux = false; //TODO: java.lang.UnsupportedOperationException: unsupported message type: OneMessageTransfer (expected: ByteBuf, DefaultFileRegion)
    this.serverBootstrap = new ServerBootstrap();
    this.nettyServerConfig = nettyServerConfig;
    this.channelEventListener = channelEventListener;

    int publicThreadNums = nettyServerConfig.getServerCallbackExecutorThreads();
    if (publicThreadNums <= 0) {
        publicThreadNums = 4;/*from   w  ww. j  a v  a 2 s  .  c  o  m*/
    }

    this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyServerPublicExecutor_" + this.threadIndex.incrementAndGet());
        }
    });

    ThreadFactory bossThreadFactory = new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, String.format("NettyBossSelector_%d", this.threadIndex.incrementAndGet()));
        }
    };

    ThreadFactory workerThreadFactory = new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);
        private int threadTotal = nettyServerConfig.getServerSelectorThreads();

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, String.format("NettyServerSelector_%d_%d", threadTotal,
                    this.threadIndex.incrementAndGet()));
        }
    };

    if (isLinux) {
        this.eventLoopGroupBoss = new EpollEventLoopGroup(1, bossThreadFactory);
        this.eventLoopGroupWorker = new EpollEventLoopGroup(nettyServerConfig.getServerSelectorThreads(),
                workerThreadFactory);
    } else {
        this.eventLoopGroupBoss = new NioEventLoopGroup(1, bossThreadFactory);
        this.eventLoopGroupWorker = new NioEventLoopGroup(nettyServerConfig.getServerSelectorThreads(),
                workerThreadFactory);
    }
}

From source file:com.ancun.netty.common.NettyBootstrapFactory.java

License:Apache License

/**
 * NIOnetty?/* w  w  w  . j a v  a  2  s  .  com*/
 *
 * @param ioThreadCount   
 * @return   NIOnetty?
  */
private ServerBootstrap newNioServerBootstrap(int ioThreadCount) {

    bossGroup = new NioEventLoopGroup(1);

    if (ioThreadCount > 0) {
        workerGroup = new NioEventLoopGroup(ioThreadCount);
    } else {
        workerGroup = new NioEventLoopGroup();
    }

    return new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
}

From source file:com.ancun.netty.common.NettyBootstrapFactory.java

License:Apache License

private ServerBootstrap newEpollServerBootstrap(int ioThreadCount) {
    bossGroup = new EpollEventLoopGroup(1);

    if (ioThreadCount > 0) {
        workerGroup = new EpollEventLoopGroup(ioThreadCount);
    } else {//w ww  .  j  a  v  a  2 s  . c o m
        workerGroup = new EpollEventLoopGroup();
    }

    return new ServerBootstrap().group(bossGroup, workerGroup).channel(EpollServerSocketChannel.class);
}

From source file:com.android.tools.idea.diagnostics.crash.LocalTestServer.java

License:Apache License

public void start() throws Exception {
    ServerBootstrap b = new ServerBootstrap();
    myEventLoopGroup = new OioEventLoopGroup();
    b.group(myEventLoopGroup).channel(OioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override//from w w  w  . j a  v a 2  s  .  c  o  m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpServerCodec());
                    // Note: Netty's decompressor uses jcraft jzlib, which is not exported as a library
                    // p.addLast(new HttpContentDecompressor());
                    p.addLast(new HttpObjectAggregator(32 * 1024)); // big enough to collect a full thread dump
                    p.addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                            ctx.flush();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            if (!(msg instanceof FullHttpRequest)) {
                                return;
                            }

                            FullHttpResponse response = myResponseSupplier.apply((FullHttpRequest) msg);
                            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,
                                    response.content().readableBytes());
                            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            ctx.write(cause.toString()).addListener(ChannelFutureListener.CLOSE);
                        }
                    });
                }
            });

    myChannel = b.bind(myPort).sync().channel();
}

From source file:com.antsdb.saltedfish.server.SaltedFish.java

License:Open Source License

/**
 * starting netty/*w  ww  .j  av a  2s .c  om*/
 * 
 * @param port
 * @throws InterruptedException 
 */
void startNetty() throws Exception {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup(this.configService.getNettyWorkerThreadPoolSize());
    _log.info("netty worker pool size: {}", workerGroup.executorCount());

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new MysqlChannelInitializer(this)).option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.

    _log.info("starting netty on port: " + this.configService.getPort());
    this.f = b.bind(this.configService.getPort()).sync();
}

From source file:com.artigile.homestats.HomeStatsServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    ArgsParser argsParser = new ArgsParser(args);
    if (argsParser.isDisplayHelp()) {
        ArgsParser.printHelp();/*from  w  ww.  ja  v  a  2  s.co  m*/
        return;
    }

    EventLoopGroup bossGroup = null;
    EventLoopGroup workerGroup = null;
    try {
        SensorMode appMode = SensorMode
                .valueOf(argsParser.getString(ArgsParser.APP_MODE_OPTION, "dev").toUpperCase());

        SensorsDataProvider sensorsDataProvider = SensorFactory.buildSensorDataProvider(appMode);
        if (sensorsDataProvider == null) {
            LOGGER.error("No sensor device available, quitting.");
            return;
        }

        final boolean printAndExit = argsParser.argumentPassed(ArgsParser.PRINT_AND_EXIT);
        if (printAndExit) {
            sensorsDataProvider.printAll();
            return;
        }

        final String dbHost = argsParser.getString(DB_HOST_OPTION, "localhost");
        final String user = argsParser.getString(DB_USER_OPTION);
        final String pwd = argsParser.getString(DB_PWD_OPTION);
        final int port = Integer.valueOf(argsParser.getString(APP_PORT_OPTION, PORT + ""));

        LOGGER.info("Connecting to {}, user {}, pwd: {}", dbHost, user, pwd);
        final DbDao dbDao = new DbDao(dbHost, user, pwd);
        new DataService(sensorsDataProvider, dbDao, 1000 * 60 * 5).start();

        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        } else {
            sslCtx = null;
        }

        // Configure the server.
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(new HomeStatsServerInitializer(sslCtx, dbDao, sensorsDataProvider));

        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 {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
}

From source file:com.athena.dolly.websocket.server.test.WebSocketServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w w w . ja  va2 s .  co m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketServerInitializer());

        Channel ch = b.bind(port).sync().channel();
        System.out.println("Web socket server started at port " + port + '.');
        System.out.println("Open your browser and navigate to http://localhost:" + port + '/');

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

From source file:com.athena.dolly.websocket.server.test.WebSocketSslServer.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*  w  w w  . j av  a2  s  .co  m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new WebSocketSslServerInitializer());

        Channel ch = b.bind(port).sync().channel();
        System.out.println("Web socket server started at port " + port + '.');
        System.out.println("Open your browser and navigate to https://localhost:" + port + '/');
        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

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

License:Open Source License

public void start() throws Exception {

    new Thread() {
        @Override/*  www .  j a v 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();
}