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.liferay.sync.engine.lan.server.file.LanFileServer.java

License:Open Source License

public void start() throws Exception {
    _childEventLoopGroup = new NioEventLoopGroup();
    _parentEventLoopGroup = new NioEventLoopGroup(1);

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverBootstrap.group(_parentEventLoopGroup, _childEventLoopGroup);
    serverBootstrap.channel(NioServerSocketChannel.class);

    _syncTrafficShapingHandler = new SyncTrafficShapingHandler(_childEventLoopGroup);

    _lanFileServerInitializer = new LanFileServerInitializer(_syncTrafficShapingHandler);

    serverBootstrap.childHandler(_lanFileServerInitializer);

    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture channelFuture = serverBootstrap.bind(PropsValues.SYNC_LAN_SERVER_PORT);

    try {//from w w w.ja va  2 s .  com
        channelFuture.sync();
    } catch (Exception e) {

        // Compiling fails when directly catching BindException. Netty seems
        // to throw an undeclared exception.

        if (e instanceof BindException) {
            channelFuture = serverBootstrap.bind(0);

            channelFuture.sync();
        } else {
            throw e;
        }
    }

    Channel channel = channelFuture.channel();

    InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.localAddress();

    _port = inetSocketAddress.getPort();

    channelFuture.sync();

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            long count = SyncFileService.getSyncFilesCount(SyncFile.UI_EVENT_DOWNLOADING,
                    SyncFile.UI_EVENT_UPLOADING);

            long writeDelay = 0;

            if (count > 0) {
                _syncTrafficShapingHandler.setWriteDelay(PropsValues.SYNC_LAN_SERVER_WRITE_DELAY);
            }

            _syncTrafficShapingHandler.setWriteDelay(writeDelay);
        }

    };

    ScheduledExecutorService scheduledExecutorService = LanEngine.getScheduledExecutorService();

    scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 500, TimeUnit.MILLISECONDS);
}

From source file:com.linecorp.armeria.server.Server.java

License:Apache License

private ChannelFuture start(ServerPort port) {
    ServerBootstrap b = new ServerBootstrap();

    b.group(bossGroup, workerGroup);//  w  w w  .j  av  a 2 s.c om
    b.channel(
            NativeLibraries.isEpollAvailable() ? EpollServerSocketChannel.class : NioServerSocketChannel.class);
    b.childHandler(new HttpServerPipelineConfigurator(config, port, sslContexts,
            Optional.ofNullable(gracefulShutdownHandler)));

    return b.bind(port.localAddress());
}

From source file:com.linkedin.mitm.proxy.ProxyServer.java

License:Open Source License

/**
 * Start proxy server// w w  w . ja  va2s.c om
 * */
public void start() throws InterruptedException {
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(_acceptorGroup, _upstreamWorkerGroup);
    serverBootstrap.channelFactory(new ChannelFactory<ServerChannel>() {
        @Override
        public ServerChannel newChannel() {
            return new NioServerSocketChannel();
        }
    });
    serverBootstrap.childHandler(new ProxyInitializer(this));

    //bind
    ChannelFuture future = serverBootstrap.bind(_host, _port);

    //wait for the future
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        future.channel().closeFuture().awaitUninterruptibly();
        throw new ChannelException(String.format("Failed to bind to: %s:%d", _host, _port), future.cause());
    } else {
        _allChannels.add(future.channel());
    }
}

From source file:com.mpush.netty.server.NettyServer.java

License:Apache License

private void createServer(final Listener listener, EventLoopGroup boss, EventLoopGroup work,
        Class<? extends ServerChannel> clazz) {
    /***/*w  w  w  .  j  av  a2s.c  o  m*/
     * NioEventLoopGroup ??I/O?
     * Netty????EventLoopGroup??????
     * ?2NioEventLoopGroup
     * ???boss??
     * ???worker???
     * boss?worker
     * ???Channels??EventLoopGroup
     * ???
     */
    this.bossGroup = boss;
    this.workerGroup = work;

    try {
        /**
         * ServerBootstrap ?NIO??
         * ??Channel
         */
        ServerBootstrap b = new ServerBootstrap();

        /**
         * groupjava.lang.IllegalStateException: group not set
         */
        b.group(bossGroup, workerGroup);

        /***
         * ServerSocketChannelNIOselector?
         * Channel?.
         */
        b.channel(clazz);

        /***
         * ?????Channel
         * ChannelInitializer?
         * ?Channel
         * ?NettyServerHandler??Channel
         * ChannelPipeline??
         * ??????pipeline
         * ??????
         */
        b.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        initOptions(b);

        /***
         * ???
         */
        ChannelFuture f = b.bind(port).sync().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    Logs.Console.error("server start success on:{}", port);
                    if (listener != null)
                        listener.onSuccess(port);
                } else {
                    Logs.Console.error("server start failure on:{}", port, future.cause());
                    if (listener != null)
                        listener.onFailure(future.cause());
                }
            }
        });
        if (f.isSuccess()) {
            serverState.set(State.Started);
            /**
             * socket
             */
            f.channel().closeFuture().sync();
        }

    } catch (Exception e) {
        logger.error("server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("server start exception, port=" + port, e);
    } finally {
        /***
         * 
         */
        stop(null);
    }
}

From source file:com.mpush.netty.server.NettyTCPServer.java

License:Apache License

private void createServer(Listener listener, EventLoopGroup boss, EventLoopGroup work,
        ChannelFactory<? extends ServerChannel> channelFactory) {
    /***//w ww.  jav a  2 s  . com
     * NioEventLoopGroup ??I/O?
     * Netty????EventLoopGroup??????
     * ?2NioEventLoopGroup
     * ???boss??
     * ???worker???
     * boss?worker
     * ???Channels??EventLoopGroup
     * ???
     */
    this.bossGroup = boss;
    this.workerGroup = work;

    try {
        /**
         * ServerBootstrap ?NIO??
         * ??Channel
         */
        ServerBootstrap b = new ServerBootstrap();

        /**
         * groupjava.lang.IllegalStateException: group not set
         */
        b.group(bossGroup, workerGroup);

        /***
         * ServerSocketChannelNIOselector?
         * Channel?.
         */
        b.channelFactory(channelFactory);

        /***
         * ?????Channel
         * ChannelInitializer?
         * ?Channel
         * ?NettyServerHandler??Channel
         * ChannelPipeline??
         * ??????pipeline
         * ??????
         */
        b.childHandler(new ChannelInitializer<Channel>() { // (4)
            @Override
            public void initChannel(Channel ch) throws Exception {//?
                initPipeline(ch.pipeline());
            }
        });

        initOptions(b);

        /***
         * ???
         */
        b.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                serverState.set(State.Started);
                logger.info("server start success on:{}", port);
                if (listener != null)
                    listener.onSuccess(port);
            } else {
                logger.error("server start failure on:{}", port, future.cause());
                if (listener != null)
                    listener.onFailure(future.cause());
            }
        });
    } catch (Exception e) {
        logger.error("server start exception", e);
        if (listener != null)
            listener.onFailure(e);
        throw new ServiceException("server start exception, port=" + port, e);
    }
}

From source file:com.mycompany.ffserver.FFServer.java

@Override
public void run() {
    FFDevice ff_device;/*  w w w  .j a  va 2s  . c om*/
    FFRequest ff_request;
    int dev_count;
    int req_count;

    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            device_lst.add(new FFDevice(ch));
            logger.info("have a new connnection");
        }
    });
    bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
    try {
        bootstrap.bind(port).sync();
    } catch (InterruptedException ex) {
        logger.error(ex.getMessage());
    }

    ResultSet rs;
    try {
        rs = DbUtils.getDeviceList();
        String reg_str;
        while (rs.next()) {
            reg_str = rs.getString("regs");
            addRegDevice(reg_str);
            DbUtils.updateAllToOffline();
        }
    } catch (ClassNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (SQLException ex) {
        logger.error(ex.getMessage());
    }

    while (!m_stop_flag) {

        dev_count = device_lst.size();

        for (int i = dev_count - 1; i >= 0; i--) {
            ff_device = (FFDevice) device_lst.get(i);

            if (ff_device.isClosed()) {
                device_lst.remove(i);
                logger.info(String.format("remove device with reg_str '%s' from device_lst",
                        ff_device.getRegStr()));
                continue;
            }

            if (ff_device.getRegStr().isEmpty()) {
                if (ff_device.connect_time + 5000 < System.currentTimeMillis()) {
                    ff_device.Close();
                    logger.info("close connection of un-reg device");
                }
                continue;
            }

            if (!dev_info.isAvailable(ff_device.getRegStr())) {
                ff_device.Close();
                logger.info(String.format("close old connection of device that have reg_str '%s'",
                        ff_device.getRegStr()));
                continue;
            }

            dev_info.lockRegStr(ff_device.getRegStr());

            req_count = req_lst.size();
            for (int j = 0; j < req_count; j++) {
                ff_request = req_lst.get(j);
                if (ff_request.reg_str.equals(ff_device.getRegStr()) && ff_device.req == null) {
                    logger.info(String.format("send req to %s", ff_device.getRegStr()));
                    ff_device.req = ff_request;
                    req_lst.remove(j);
                    break;
                }
            }

            ff_device.Process();
        }

        dev_info.freeAllRegStr();

        try {
            Thread.sleep(10);
        } catch (InterruptedException ex) {
            logger.error(ex.getMessage());
        }
    }
}

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

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/* w w  w. 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();
    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.out.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.netty.fileTest.http.upload.HttpUploadServer.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w  ww .  j a  va2s. c  o  m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } 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.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServer.java

License:Apache License

@Override
protected void doStart() throws Exception {
    final SslContext sslCtx;
    if (SSL) {/*from w ww .j  ava2s .  c  om*/
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    boss = new NioEventLoopGroup();
    worker = new NioEventLoopGroup();
    try {

        ServerBootstrap server = new ServerBootstrap();
        server.group(boss, worker);
        server.channel(NioServerSocketChannel.class);
        server.handler(new LoggingHandler(LogLevel.INFO));
        server.childHandler(new HttpUploadServerInitializer(sslCtx, fileService, fileRecordManager));

        Channel ch = server.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 {
        boss.shutdownGracefully();
        worker.shutdownGracefully();
    }
}

From source file:com.openddal.server.NettyServer.java

License:Apache License

private ServerBootstrap configServer() {
    bossGroup = new NioEventLoopGroup(args.bossThreads, new DefaultThreadFactory("NettyBossGroup", true));
    workerGroup = new NioEventLoopGroup(args.workerThreads, new DefaultThreadFactory("NettyWorkerGroup", true));
    userExecutor = createUserThreadExecutor();
    Authenticator authenticator = createAuthenticator();
    ProcessorFactory processorFactory = createProcessorFactory();
    RequestFactory requestFactory = createRequestFactory();
    ResponseFactory responseFactory = createResponseFactory();
    final ProtocolHandler protocolHandler = new ProtocolHandler(authenticator, processorFactory, requestFactory,
            responseFactory, userExecutor);

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true);

    if (args.socketTimeoutMills > 0) {
        b.childOption(ChannelOption.SO_TIMEOUT, args.socketTimeoutMills);
    }/*from   w w w .j  a  v  a 2  s. c o m*/

    if (args.recvBuff > 0) {
        b.childOption(ChannelOption.SO_RCVBUF, args.recvBuff);
    }

    if (args.sendBuff > 0) {
        b.childOption(ChannelOption.SO_SNDBUF, args.sendBuff);
    }

    b.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(createProtocolDecoder(), /* createProtocolEncoder(), */ protocolHandler);
        }
    });

    return b;
}