Example usage for io.netty.bootstrap ServerBootstrap childOption

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

Introduction

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

Prototype

public <T> ServerBootstrap childOption(ChannelOption<T> childOption, T value) 

Source Link

Document

Allow to specify a ChannelOption which is used for the Channel instances once they get created (after the acceptor accepted the Channel ).

Usage

From source file:com.kixeye.kixmpp.p2p.node.NodeServer.java

License:Apache License

public void initialize(final String host, final int port, final EventLoopGroup bossGroup,
        final EventLoopGroup workerGroup, final MessageRegistry messageRegistry,
        final ChannelInboundHandlerAdapter channelListener) {
    ServerBootstrap boot = new ServerBootstrap();
    boot.group(bossGroup, workerGroup);//  www. jav a2s  . c  o  m
    boot.channel(NioServerSocketChannel.class);
    boot.option(ChannelOption.SO_BACKLOG, 32);
    boot.childOption(ChannelOption.SO_KEEPALIVE, true);
    boot.childOption(ChannelOption.TCP_NODELAY, true);
    boot.childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();

            //p.addLast(new LoggingHandler());

            // encoders
            p.addLast(new LengthFieldPrepender(4));
            p.addLast(new ProtostuffEncoder(messageRegistry));

            // decoders
            p.addLast(new LengthFieldBasedFrameDecoder(0x100000, 0, 4, 0, 4));
            p.addLast(new ProtostuffDecoder(messageRegistry));
            p.addLast(channelListener);
        }
    });

    // start accepting connection
    try {
        logger.info("Starting NodeServer on [{}]...", port);

        if (host == null) {
            acceptChannel = boot.bind(port).sync().channel();
        } else {
            acceptChannel = boot.bind(host, port).sync().channel();
        }

        logger.info("NodeServer listening on [{}]...", port);
    } catch (InterruptedException e) {
        logger.error("Binding to port {} failed", port, e);
    }

}

From source file:com.liferay.nativity.control.findersync.FSNativityControlImpl.java

License:Open Source License

@Override
public boolean connect() {
    if (_connected) {
        return true;
    }//from   w  w w .  jav a 2 s .c  o m

    _childEventLoopGroup = new NioEventLoopGroup();
    _parentEventLoopGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(_parentEventLoopGroup, _childEventLoopGroup);

        serverBootstrap.channel(NioServerSocketChannel.class);

        ChannelInitializer channelInitializer = new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {

                DelimiterBasedFrameDecoder messageDecoder = new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,
                        Delimiters.lineDelimiter());

                FinderSyncChannelHandler finderSyncChannelHandler = new FinderSyncChannelHandler();

                socketChannel.pipeline().addLast(messageDecoder, finderSyncChannelHandler);
            }
        };

        serverBootstrap.childHandler(channelInitializer);

        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture channelFuture = serverBootstrap.bind(0).sync();

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

        _writePortToFile(inetSocketAddress.getPort());
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);

        _connected = false;

        return false;
    }

    _connected = true;

    return true;
}

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 {//  w  w  w . j ava  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.moshi.receptionist.remoting.netty.NettyRemotingServer.java

License:Apache License

@Override
public void start() {
    this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(//
            nettyServerConfig.getServerWorkerThreads(), //
            new ThreadFactory() {

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//  w  ww.  j  a v  a  2 s .  com
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroup, new NioEventLoopGroup())
                    .channel(NioServerSocketChannel.class)
                    //
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //
                    .childOption(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize)
                    //
                    .childOption(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize)

                    .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort()))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    //
                                    defaultEventExecutorGroup, //
                                    new NettyEncoder(), //
                                    new NettyDecoder(), //
                                    new IdleStateHandler(0, 0,
                                            nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //
                                    new NettyConnetManageHandler(), //
                                    new NettyServerHandler());
                        }
                    });

    if (NettySystemConfig.NettyPooledByteBufAllocatorEnable) {
        // ????
        childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
        ;
    }

    try {
        ChannelFuture sync = this.serverBootstrap.bind().sync();
        InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress();
        this.port = addr.getPort();
    } catch (InterruptedException e1) {
        throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1);
    }

    if (this.channelEventListener != null) {
        this.nettyEventExecuter.start();
    }

    // ?1??
    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            try {
                NettyRemotingServer.this.scanResponseTable();
            } catch (Exception e) {
                log.error("scanResponseTable exception", e);
            }
        }
    }, 1000 * 3, 1000);
}

From source file:com.mpush.core.server.ConnectionServer.java

License:Apache License

@Override
protected void initOptions(ServerBootstrap b) {
    super.initOptions(b);

    b.option(ChannelOption.SO_BACKLOG, 1024);

    /**//from w  ww.  j a  v a2  s  . co  m
     * TCP????
     * NettyChannelOptionSO_SNDBUFSO_RCVBUF
     * ????????32K?
     */
    if (snd_buf.connect_server > 0)
        b.childOption(ChannelOption.SO_SNDBUF, snd_buf.connect_server);
    if (rcv_buf.connect_server > 0)
        b.childOption(ChannelOption.SO_RCVBUF, rcv_buf.connect_server);

    /**
     * ??????????
     * ???????????????
     * ????????
     * ????????
     * ??????
     * ???NettyChannelOutboundBuffer
     * buffernetty?channel write?buffer???????(?channelbuffer)
     * ??32(32?)32?
     * ?(?TCP??)
     * ??buffer???(?swap?linux killer)
     * ?channel?channel?active?
     *
     * ChannelOutboundBuffer????
     * buffer??channelisWritable??false
     * buffer??isWritable??trueisWritablefalse????
     * ???64K?32K???????
     */
    b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
            new WriteBufferWaterMark(connect_server_low, connect_server_high));
}

From source file:com.mpush.core.server.GatewayServer.java

License:Apache License

@Override
protected void initOptions(ServerBootstrap b) {
    super.initOptions(b);
    if (snd_buf.gateway_server > 0)
        b.childOption(ChannelOption.SO_SNDBUF, snd_buf.gateway_server);
    if (rcv_buf.gateway_server > 0)
        b.childOption(ChannelOption.SO_RCVBUF, rcv_buf.gateway_server);
    /**/*from  w ww.j  a  v  a 2s.c om*/
     * ??????????
     * ???????????????
     * ????????
     * ????????
     * ??????
     * ???NettyChannelOutboundBuffer
     * buffernetty?channel write?buffer???????(?channelbuffer)
     * ??32(32?)32?
     * ?(?TCP??)
     * ??buffer???(?swap?linux killer)
     * ?channel?channel?active?
     *
     * ChannelOutboundBuffer????
     * buffer??channelisWritable??false
     * buffer??isWritable??trueisWritablefalse????
     * ???64K?32K???????
     */
    if (gateway_server_low > 0 && gateway_server_high > 0) {
        b.childOption(ChannelOption.WRITE_BUFFER_WATER_MARK,
                new WriteBufferWaterMark(gateway_server_low, gateway_server_high));
    }
}

From source file:com.mpush.core.server.WebSocketServer.java

License:Apache License

@Override
protected void initOptions(ServerBootstrap b) {
    super.initOptions(b);
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.childOption(ChannelOption.SO_SNDBUF, 32 * 1024);
    b.childOption(ChannelOption.SO_RCVBUF, 32 * 1024);
}

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

License:Apache License

protected void initOptions(ServerBootstrap b) {

    /***//from  ww w.j  ava 2 s .c  o m
     * option()??NioServerSocketChannel??
     * childOption()???ServerChannel
     * ?NioServerSocketChannel
     */
    b.childOption(ChannelOption.SO_KEEPALIVE, true);

    /**
     * Netty 4ByteBufJava jemalloc Facebook
     * Netty?????GC????
     * ???
     * Netty???
     */
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}

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

License:Apache License

/***
 * option()??NioServerSocketChannel??/*  w  w w  .  j a va  2 s. com*/
 * childOption()???ServerChannel
 * ?NioServerSocketChannel
 */
protected void initOptions(ServerBootstrap b) {
    //b.childOption(ChannelOption.SO_KEEPALIVE, false);// 

    /**
     * Netty 4ByteBufJava jemalloc Facebook
     * Netty?????GC????
     * ???
     * Netty???
     */
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
}

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

@Override
public void run() {
    FFDevice ff_device;/*from www .  j  av  a 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());
        }
    }
}