Example usage for io.netty.handler.timeout IdleStateHandler IdleStateHandler

List of usage examples for io.netty.handler.timeout IdleStateHandler IdleStateHandler

Introduction

In this page you can find the example usage for io.netty.handler.timeout IdleStateHandler IdleStateHandler.

Prototype

public IdleStateHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) 

Source Link

Document

Creates a new instance firing IdleStateEvent s.

Usage

From source file:cc.ly.mc.server.netty.SocketServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("idleStateHandler", new IdleStateHandler(0, 3, 0));
    pipeline.addLast("heartbeat", new HeartbeatHandler());
    pipeline.addLast("decoder", new SocketDecoder());
    pipeline.addLast("encoder", new SocketEncoder());
    pipeline.addLast("handler", new SocketServerHandler());
}

From source file:club.lovety.xy.netty.test.UptimeClient.java

License:Apache License

static Bootstrap configureBootstrap(Bootstrap b, EventLoopGroup g) {
    b.group(g).channel(NioSocketChannel.class).remoteAddress(HOST, PORT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from ww w .ja  va2s  .co m
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 0, 0), handler);
                }
            });
    return b;
}

From source file:com.alibaba.dubbo.qos.server.handler.QosProcessHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 1) {
        return;/* w w  w.  j  a va2  s  . co  m*/
    }

    // read one byte to guess protocol
    final int magic = in.getByte(in.readerIndex());

    ChannelPipeline p = ctx.pipeline();
    p.addLast(new LocalHostPermitHandler(acceptForeignIp));
    if (isHttp(magic)) {
        // no welcome output for http protocol
        if (welcomeFuture != null && welcomeFuture.isCancellable()) {
            welcomeFuture.cancel(false);
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpProcessHandler());
        p.remove(this);
    } else {
        p.addLast(new LineBasedFrameDecoder(2048));
        p.addLast(new StringDecoder(CharsetUtil.UTF_8));
        p.addLast(new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new IdleStateHandler(0, 0, 5 * 60));
        p.addLast(new TelnetProcessHandler());
        p.remove(this);
    }
}

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

License:Apache License

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

                private AtomicInteger threadIndex = new AtomicInteger(0);

                @Override//w ww .j a va2  s  . c  om
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker);//
    if (isLinux) {
        handler.channel(EpollSocketChannel.class);
    } else {
        handler.channel(NioSocketChannel.class);
    }
    //
    handler.option(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize())
            //
            .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize())
            //
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(//
                            defaultEventExecutorGroup, //
                            new NettyEncoder(), //
                            new NettyDecoder(), //
                            new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), //
                            new NettyConnetManageHandler(), //
                            new NettyClientHandler());
                }
            });

    this.timer.scheduleAtFixedRate(new TimerTask() {

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

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

From source file:com.alibaba.rocketmq.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/*from  w  ww . jav a  2s . c o m*/
                public Thread newThread(Runnable r) {
                    return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet());
                }
            });

    ServerBootstrap childHandler = //
            this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker);
    if (isLinux) {
        childHandler.channel(EpollServerSocketChannel.class);
    } else {
        childHandler.channel(NioServerSocketChannel.class);
    }
    if (isLinux) {
        childHandler.option(EpollChannelOption.SO_REUSEPORT, true);
    }
    //
    childHandler.option(ChannelOption.SO_BACKLOG, 1024)
            //
            .option(ChannelOption.SO_REUSEADDR, true)
            //
            .option(ChannelOption.SO_KEEPALIVE, false)
            //
            .childOption(ChannelOption.TCP_NODELAY, true)
            //
            .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize())
            //
            .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize())
            //
            .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 (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) {
        // ????
        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.alltobid.quotabid.BidServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();/*from w  w  w . j  av  a 2 s. c om*/

    p.addLast(new IdleStateHandler(20, 0, 0));

    p.addLast(loggingHandler);
    p.addLast(SocketServer.globalTrafficShapingHandler);

    p.addLast(stringEncoder);

    p.addLast(SocketServer.bidServerHandler);
}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcClientPipelineinitializer.java

License:Apache License

/**
 * @brief ??//from w  w w  .  j  a v a 2 s  .  c  o m
 * @return ChannelPipeline
 * @throws Exception
 * @author songhuiqing
 * @date 2013/03/07 11:14:53
 */
@Override
protected void initChannel(Channel ch) throws Exception {
    LOG.log(Level.FINEST, "begin process RPC server response to client handler");
    ChannelPipeline channelPipe = ch.pipeline();
    int idleTimeout = this.rpcClient.getRpcClientOptions().getIdleTimeout();
    channelPipe.addFirst(RPC_CHANNEL_STATE_AWARE_HANDLER,
            new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout));
    channelPipe.addFirst(RPC_CHANNEL_IDLE_HANDLER, new RpcServerChannelIdleHandler());

    // check if need to compress for data and attachment
    channelPipe.addFirst(COMPRESS, new RpcDataPackageCompressHandler());
    // encode RpcDataPackage to byte array
    channelPipe.addFirst(CLIENT_ENCODER,
            new RpcDataPackageEncoder(rpcClient.getRpcClientOptions().getChunkSize()));

    // receive data from server
    // receive byte array to encode to RpcDataPackage
    channelPipe.addLast(CLIENT_DECODER, new RpcDataPackageDecoder(-1));
    // do uncompress handle
    channelPipe.addLast(UNCOMPRESS, new RpcDataPackageUnCompressHandler());
    // do client handler
    channelPipe.addLast(CLIENT_HANDLER, new RpcClientServiceHandler(rpcClient));

}

From source file:com.baidu.jprotobuf.pbrpc.transport.RpcServerPipelineInitializer.java

License:Apache License

@Override
protected void initChannel(Channel ch) throws Exception {
    LOG.log(Level.FINE, "begin process RPC server handler");
    ChannelPipeline channelPipe = ch.pipeline();
    // receive request data
    channelPipe.addLast(RPC_CHANNEL_STATE_AWARE_HANDLER,
            new IdleStateHandler(this.rpcServerOptions.getKeepAliveTime(),
                    this.rpcServerOptions.getKeepAliveTime(), this.rpcServerOptions.getKeepAliveTime()));

    channelPipe.addLast(RPC_CHANNEL_IDLE_HANDLER, new RpcServerChannelIdleHandler());

    RpcDataPackageDecoder rpcDataPackageDecoder = new RpcDataPackageDecoder(
            this.rpcServerOptions.getChunkPackageTimeout());
    rpcDataPackageDecoderList.add(rpcDataPackageDecoder);
    // receive byte array to encode to RpcDataPackage
    channelPipe.addLast(DECODER, rpcDataPackageDecoder);
    // do uncompress handle
    channelPipe.addLast(UNCOMPRESS, new RpcDataPackageUnCompressHandler());
    // to process RPC service handler of request object RpcDataPackage and
    // return new RpcDataPackage
    channelPipe.addLast(RPC_SERVER_HANDLER, new RpcServiceHandler(this.rpcServiceRegistry));

    // response back
    // check if need to compress for data and attachment
    channelPipe.addFirst(COMPRESS, new RpcDataPackageCompressHandler());
    // encode RpcDataPackage to byte array
    channelPipe.addFirst(SERVER_DATA_PACK, new RpcDataPackageEncoder());

}

From source file:com.bloom.zerofs.rest.NettyServerFactory.java

License:Open Source License

/**
 * Creates a new instance of NettyServerFactory.
 * @param verifiableProperties the in-memory {@link VerifiableProperties} to use.
 * @param metricRegistry the {@link MetricRegistry} to use.
 * @param requestHandler the {@link RestRequestHandler} to hand off the requests to.
 * @param publicAccessLogger the {@link PublicAccessLogger} that can be used for public access logging
 * @param restServerState the {@link RestServerState} that can be used to check the health of the system
 *                              to respond to health check requests
 * @throws IllegalArgumentException if any of the arguments are null.
 *//*from w w  w. j  a va  2s .c  o  m*/
public NettyServerFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry,
        final RestRequestHandler requestHandler, final PublicAccessLogger publicAccessLogger,
        final RestServerState restServerState) {
    if (verifiableProperties == null || metricRegistry == null || requestHandler == null
            || publicAccessLogger == null || restServerState == null) {
        throw new IllegalArgumentException("Null arg(s) received during instantiation of NettyServerFactory");
    } else {
        nettyConfig = new NettyConfig(verifiableProperties);
        nettyMetrics = new NettyMetrics(metricRegistry);
        final ConnectionStatsHandler connectionStatsHandler = new ConnectionStatsHandler(nettyMetrics);
        channelInitializer = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ch.pipeline()
                        // connection stats handler to track connection related metrics
                        .addLast("connectionStatsHandler", connectionStatsHandler)
                        // for http encoding/decoding. Note that we get content in 8KB chunks and a change to that number has
                        // to go here.
                        .addLast("codec", new HttpServerCodec(nettyConfig.nettyServerMaxInitialLineLength,
                                nettyConfig.nettyServerMaxHeaderSize, nettyConfig.nettyServerMaxChunkSize))
                        // for health check request handling
                        .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics))
                        // for public access logging
                        .addLast("publicAccessLogHandler",
                                new PublicAccessLogHandler(publicAccessLogger, nettyMetrics))
                        // for detecting connections that have been idle too long - probably because of an error.
                        .addLast("idleStateHandler",
                                new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds))
                        // for safe writing of chunks for responses
                        .addLast("chunker", new ChunkedWriteHandler())
                        // custom processing class that interfaces with a BlobStorageService.
                        .addLast("processor",
                                new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler));
            }
        };
    }
}

From source file:com.cmz.uptime.UptimeClient.java

License:Apache License

static Bootstrap configureBootstrap(Bootstrap b, EventLoopGroup g) {
    b.group(g).channel(NioSocketChannel.class).remoteAddress(HOST, PORT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override/*from  w w w  . ja  va2s.c  om*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 0, 0), handler);
                }
            });

    return b;
}