Example usage for io.netty.channel ChannelOption SO_KEEPALIVE

List of usage examples for io.netty.channel ChannelOption SO_KEEPALIVE

Introduction

In this page you can find the example usage for io.netty.channel ChannelOption SO_KEEPALIVE.

Prototype

ChannelOption SO_KEEPALIVE

To view the source code for io.netty.channel ChannelOption SO_KEEPALIVE.

Click Source Link

Usage

From source file:com.mpush.netty.client.NettyClient.java

License:Apache License

@Override
public void start(final Listener listener) {
    if (started.compareAndSet(false, true)) {
        Bootstrap bootstrap = new Bootstrap();
        workerGroup = new NioEventLoopGroup();
        bootstrap.group(workerGroup)//
                .option(ChannelOption.TCP_NODELAY, true)//
                .option(ChannelOption.SO_REUSEADDR, true)//
                .option(ChannelOption.SO_KEEPALIVE, true)//
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)//
                .channel(NioSocketChannel.class).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() { // (4)
            @Override/*  w  w  w. j a v  a 2s . co  m*/
            public void initChannel(SocketChannel ch) throws Exception {
                initPipeline(ch.pipeline());
            }
        });

        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    if (listener != null)
                        listener.onSuccess(port);
                    LOGGER.info("start netty client success, host={}, port={}", host, port);
                } else {
                    if (listener != null)
                        listener.onFailure(future.cause());
                    LOGGER.error("start netty client failure, host={}, port={}", host, port, future.cause());
                }
            }
        });
    } else {
        listener.onFailure(new ServiceException("client has started!"));
    }
}

From source file:com.mpush.netty.http.NettyHttpClient.java

License:Apache License

@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);/* w  w  w .java2  s  .  c om*/
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}

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

License:Apache License

protected void initOptions(ServerBootstrap b) {

    /***//from w  ww.  j  a  va2 s .  c om
     * 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.my.netty.object.ObjectEchoClient.java

License:Apache License

public void run() throws Exception {
    Bootstrap b = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/*from   w ww. ja v  a  2  s  .co  m*/
        b.group(workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ObjectEncoder())
                                .addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                                .addLast(new ObjectEchoClientHandler(firstMessageSize));
                    }
                });

        // Start the connection attempt.
        System.out.println("client prepare connect");
        ChannelFuture f1 = b.connect(host, port).sync();
        ChannelFuture f2 = b.connect(host, port).sync();

        f1.channel().closeFuture().sync();
        f2.channel().closeFuture().sync();
    } finally {
        System.out.println("client do finally");
        workerGroup.shutdownGracefully();
        System.out.println("client closing");
    }
}

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

@Override
public void run() {
    FFDevice ff_device;/*from   w  w w  .  ja va 2  s  .c  o  m*/
    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.navercorp.nbasearc.gcp.PhysicalConnection.java

License:Apache License

static PhysicalConnection create(String ip, int port, SingleThreadEventLoop eventLoop, Gateway gw,
        int reconnectInterval) {
    final PhysicalConnection pc = new PhysicalConnection(ip, port, eventLoop, gw, reconnectInterval);

    pc.b.group(eventLoop.getEventLoopGroup()).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
            .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_LINGER, 0)
            .option(ChannelOption.SO_SNDBUF, SOCKET_BUFFER).option(ChannelOption.SO_RCVBUF, SOCKET_BUFFER)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*  ww w.  j a  va 2 s  .  c  o m*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(pc.new PhysicalConnectionHandler());
                }
            });

    return pc;
}

From source file:com.netty.HttpHelloWorldServer.java

License:Apache License

public void start(String[] args) throws Exception {

    initSpringContext(args);//  w w  w.  j  a v a  2  s  .c  o m
    // 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(1000);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                //                    .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new HttpHelloWorldServerInitializer(applicationContext, sslCtx));
        b.option(ChannelOption.SO_BACKLOG, 128); // (5)
        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
        b.childOption(ChannelOption.SO_KEEPALIVE, true);
        b.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
        b.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);

        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.nettyhttpserver.server.NettyServer.java

public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {//from w  w  w. j av  a 2  s  .c om
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new NettyServerInitializer()).option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        ChannelFuture cf = b.bind(port).sync();
        cf.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:com.newlandframework.avatarmq.broker.server.AvatarMQBrokerServer.java

License:Apache License

public void init() {
    try {/*from  w  w w  . j a va  2s . c  om*/
        handler = new MessageBrokerHandler().buildConsumerHook(new ConsumerMessageHook())
                .buildProducerHook(new ProducerMessageHook());

        boss = new NioEventLoopGroup(1, threadBossFactory);

        workers = new NioEventLoopGroup(parallel, threadWorkerFactory, NettyUtil.getNioSelectorProvider());

        KryoCodecUtil util = new KryoCodecUtil(KryoPoolFactory.getKryoPoolInstance());

        bootstrap = new ServerBootstrap();

        bootstrap.group(boss, workers).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, false).childOption(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_SNDBUF, nettyClustersConfig.getClientSocketSndBufSize())
                .option(ChannelOption.SO_RCVBUF, nettyClustersConfig.getClientSocketRcvBufSize())
                .handler(new LoggingHandler(LogLevel.INFO)).localAddress(serverIpAddr)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(defaultEventExecutorGroup, new MessageObjectEncoder(util),
                                new MessageObjectDecoder(util), handler);
                    }
                });

        super.init();
    } catch (IOException ex) {
        Logger.getLogger(AvatarMQBrokerServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.newlandframework.avatarmq.netty.MessageConnectFactory.java

License:Apache License

public void init() {
    try {//from  w  w w .ja v  a  2 s.  com
        defaultEventExecutorGroup = new DefaultEventExecutorGroup(NettyClustersConfig.getWorkerThreads(),
                threadFactory);
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(defaultEventExecutorGroup);
                        channel.pipeline().addLast(new MessageObjectEncoder(util));
                        channel.pipeline().addLast(new MessageObjectDecoder(util));
                        channel.pipeline().addLast(messageHandler);
                    }
                }).option(ChannelOption.SO_SNDBUF, nettyClustersConfig.getClientSocketSndBufSize())
                .option(ChannelOption.SO_RCVBUF, nettyClustersConfig.getClientSocketRcvBufSize())
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, false);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}