Example usage for io.netty.handler.timeout IdleState ALL_IDLE

List of usage examples for io.netty.handler.timeout IdleState ALL_IDLE

Introduction

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

Prototype

IdleState ALL_IDLE

To view the source code for io.netty.handler.timeout IdleState ALL_IDLE.

Click Source Link

Document

No data was either received or sent for a while.

Usage

From source file:cn.savor.small.netty.MiniProNettyClientHandler.java

License:Open Source License

@Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        String channelId = ctx.channel().id().toString();
        if (evt instanceof IdleStateEvent) {

            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state().equals(IdleState.READER_IDLE)) {
                //?
                LogUtils.i("READER_IDLE");
                LogFileUtil.write("MiniNettyClientHandler READER_IDLE");

            } else if (event.state().equals(IdleState.WRITER_IDLE)) {

                LogUtils.i("WRITER_IDLE");
                LogFileUtil.write("MiniNettyClientHandler WRITER_IDLE");
                try {
                    // ???
                    MessageBean message = new MessageBean();
                    message.setCmd(MessageBean.Action.HEART_CLENT_TO_SERVER);
                    String number = channelId + System.currentTimeMillis();
                    message.setSerialnumber(number);
                    message.setIp(AppUtils.getLocalIPAddress());
                    message.setMac(session.getEthernetMac());
                    InnerBean bean = new InnerBean();
                    bean.setHotelId(session.getBoiteId());
                    bean.setRoomId(session.getRoomId());
                    bean.setSsid(AppUtils.getShowingSSID(mContext));
                    bean.setBoxId(session.getBoxId());
                    ArrayList<String> contList = new ArrayList<>();
                    contList.add("I am a mini Heart Pakage...");
                    contList.add(new Gson().toJson(bean));
                    message.setContent(contList);
                    ChannelFuture future = ctx.writeAndFlush(message);
                    if (!future.isSuccess()) {
                        close(ctx);//from  ww  w . j av a  2 s.  c o m
                    }
                    LogUtils.v("miniProgram--WRITER_IDLE====" + channelId + "====>>>>...??:"
                            + message.getSerialnumber());
                    LogUtils.v("miniProgram--future.isSuccess()====" + future.isSuccess());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                //
                //?REQ==========
                LogUtils.i("ALL_IDLE");
                close(ctx);
            }

        }
    }

From source file:cn.savor.small.netty.NettyClientHandler.java

License:Open Source License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    super.userEventTriggered(ctx, evt);
    String channelId = ctx.channel().id().toString();
    if (evt instanceof IdleStateEvent) {

        IdleStateEvent event = (IdleStateEvent) evt;

        if (event.state().equals(IdleState.READER_IDLE)) {
            //?/*from  ww w .  j av a2 s.  co  m*/
            LogUtils.i("READER_IDLE");
            LogFileUtil.write("NettyClientHandler READER_IDLE");

        } else if (event.state().equals(IdleState.WRITER_IDLE)) {

            LogUtils.i("WRITER_IDLE");
            LogFileUtil.write("NettyClientHandler WRITER_IDLE");
            //?REQ==========
            LogUtils.i("ALL_IDLE");
            // ???
            MessageBean message = new MessageBean();
            message.setCmd(MessageBean.Action.HEART_CLENT_TO_SERVER);
            String number = channelId + System.currentTimeMillis();
            message.setSerialnumber(number);
            message.setIp(AppUtils.getLocalIPAddress());
            message.setMac(session.getEthernetMac());
            InnerBean bean = new InnerBean();
            bean.setHotelId(session.getBoiteId());
            bean.setRoomId(session.getRoomId());
            bean.setSsid(AppUtils.getShowingSSID(mContext));
            bean.setBoxId(session.getBoxId());
            ArrayList<String> contList = new ArrayList<String>();
            contList.add("I am a Heart Pakage...");
            contList.add(new Gson().toJson(bean));
            message.setContent(contList);
            ctx.writeAndFlush(message);
            LogUtils.v("????====" + channelId + "====>>>>.....??:"
                    + message.getSerialnumber());
            LogFileUtil.write("NettyClientHandler ????====" + channelId
                    + "====>>>>.....??:" + message.getSerialnumber());
        } else if (event.state().equals(IdleState.ALL_IDLE)) {
            //
            close(ctx);
        }

    }
}

From source file:com.caricah.iotracah.server.netty.TimeoutHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    super.userEventTriggered(ctx, evt);
    if (evt instanceof IdleStateEvent) {
        IdleState e = ((IdleStateEvent) evt).state();
        if (e == IdleState.ALL_IDLE) {
            //fire a channelInactive to trigger publish of Will
            ctx.fireChannelInactive();/*w w  w  . jav a  2  s  .c o m*/
            ctx.close();
        }
    }
}

From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerHandler.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (event.state().equals(IdleState.READER_IDLE)) {
            ///* ww  w. j  a va  2 s . c  o  m*/
        } else if (event.state().equals(IdleState.WRITER_IDLE)) {
            //
        } else if (event.state().equals(IdleState.ALL_IDLE)) {
            // ??
            String heart = Convert.Encode(new AssembleHeart().Assemble("", null));
            ctx.channel().writeAndFlush(heart);
        }
    }
    super.userEventTriggered(ctx, evt);
}

From source file:com.eucalyptus.ws.IoHandlers.java

License:Open Source License

public static Map<String, ChannelHandler> channelMonitors(final TimeUnit unit, final long timeout) {
    final Map<String, ChannelHandler> monitors = Maps.newHashMap();
    monitors.put("idlehandler", new IdleStateHandler(0L, 0L, timeout, unit));
    monitors.put("idlecloser", new ChannelInboundHandlerAdapter() {
        @Override/*  w ww  .  j a  v  a2s  . c  o  m*/
        public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                if (e.state() == IdleState.ALL_IDLE) {
                    ctx.channel().close();
                }
            }
        }
    });
    monitors.putAll(extraMonitors);
    return monitors;
}

From source file:com.github.ambry.rest.NettyMessageProcessor.java

License:Open Source License

/**
 * Netty calls this function when events that we have registered for, occur (in this case we are specifically waiting
 * for {@link IdleStateEvent} so that we close connections that have been idle too long - maybe due to client failure)
 * @param ctx The {@link ChannelHandlerContext} that can be used to perform operations on the channel.
 * @param event The event that occurred.
 *//*from  w  w  w  .  j  av a2s. c om*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object event) {
    // NOTE: This is specifically in place to handle connections that close unexpectedly from the client side.
    // Even in that situation, any cleanup code that we have in the handlers will have to be called.
    // This ensures that multiple chunk requests that a handler may be tracking is cleaned up properly. We need this
    // especially because request handlers handle multiple requests at the same time and might have some state for each
    // connection.
    if (event instanceof IdleStateEvent && ((IdleStateEvent) event).state() == IdleState.ALL_IDLE) {
        logger.info("Channel {} has been idle for {} seconds. Closing it", ctx.channel(),
                nettyConfig.nettyServerIdleTimeSeconds);
        nettyMetrics.idleConnectionCloseCount.inc();
        if (request != null) {
            onRequestAborted(new ClosedChannelException());
        }
    }
}

From source file:com.github.nettybook.ch7.junit.TelnetServerHandlerV3.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent e = (IdleStateEvent) evt;

        if (e.state() == IdleState.ALL_IDLE) {
            ctx.writeAndFlush("All IDLE " + new Date().toString() + "\r\n");
            //log.info("All " + e.toString());
        } else if (e.state() == IdleState.READER_IDLE) {
            //log.info("Read " +e.toString());
            ctx.writeAndFlush("READER IDLE " + new Date().toString() + "\r\n");
        } else if (e.state() == IdleState.WRITER_IDLE) {
            //log.info("Write " +e.toString());
            ctx.writeAndFlush("WRITER IDLE" + new Date().toString() + " \r\n");
        } else {/*from   ww w  .j a v a  2s . c o  m*/
            //log.info("What the " +e.toString());
            ctx.writeAndFlush(" IDLE \n");
        }

    }
}

From source file:com.github.sparkfy.network.server.TransportChannelHandler.java

License:Apache License

/** Triggered based on events from an {@link io.netty.handler.timeout.IdleStateHandler}. */
@Override/*from www .  ja v  a  2s  .  c  o m*/
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent e = (IdleStateEvent) evt;
        // See class comment for timeout semantics. In addition to ensuring we only timeout while
        // there are outstanding requests, we also do a secondary consistency check to ensure
        // there's no race between the idle timeout and incrementing the numOutstandingRequests
        // (see SPARK-7003).
        //
        // To avoid a race between TransportClientFactory.createClient() and this code which could
        // result in an inactive client being returned, this needs to run in a synchronized block.
        synchronized (this) {
            boolean isActuallyOverdue = System.nanoTime()
                    - responseHandler.getTimeOfLastRequestNs() > requestTimeoutNs;
            if (e.state() == IdleState.ALL_IDLE && isActuallyOverdue) {
                if (responseHandler.numOutstandingRequests() > 0) {
                    String address = NettyUtils.getRemoteAddress(ctx.channel());
                    logger.error("Connection to {} has been quiet for {} ms while there are outstanding "
                            + "requests. Assuming connection is dead; please adjust spark.network.timeout if this "
                            + "is wrong.", address, requestTimeoutNs / 1000 / 1000);
                    client.timeOut();
                    ctx.close();
                } else if (closeIdleConnections) {
                    // While CloseIdleConnections is enable, we also close idle connection
                    client.timeOut();
                    ctx.close();
                }
            }
        }
    }
    ctx.fireUserEventTriggered(evt);
}

From source file:com.google.cloud.pubsub.proxy.moquette.MoquetteIdleTimeoutHandler.java

License:Open Source License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleState state = ((IdleStateEvent) evt).state();
        if (state == IdleState.ALL_IDLE) {
            //fire a channelInactive to trigger publish of Will
            ctx.fireChannelInactive();/* ww w. j  a  v a 2  s . co  m*/
            ctx.close();
        } /*else if (e.getState() == IdleState.WRITER_IDLE) {
            ctx.writeAndFlush(new PingMessage());
          }*/
    }
}

From source file:com.mycompany.device.FFDevice.java

public FFDevice(SocketChannel ch) {
    this.req = null;
    this.soc = ch;
    this.data_rcv = soc.alloc().buffer(512);
    this.reg_str = "";
    this.connect_time = System.currentTimeMillis();

    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast(new IdleStateHandler(0, 0, idle_time_interval_s));
    pipeline.addLast(new MessageToByteEncoder<byte[]>() {
        @Override/* ww  w  . j  av  a2  s.c  om*/
        protected void encode(ChannelHandlerContext ctx, byte[] msg, ByteBuf out) throws Exception {
            // TODO Auto-generated method stub
            out.writeBytes(msg);
        }
    });
    pipeline.addLast(new ChannelInboundHandlerAdapter() {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            // TODO Auto-generated method stub
            ByteBuf bb = (ByteBuf) msg;
            if (reg_str.equals("")) {
                reg_str = bb.toString(Charset.defaultCharset());
                FFServer.logger.info(String.format("device that has regs %s is registed", reg_str));
            } else {
                FFServer.logger.debug(String.format("%s receive: %d bytes", reg_str, bb.readableBytes()));
                data_rcv.writeBytes(bb);
            }
            ReferenceCountUtil.release(msg);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // TODO Auto-generated method stub
            FFServer.logger.error(cause);
            Close();
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.ALL_IDLE) {
                    FFServer.logger.info(String.format("%s in idle state", reg_str));

                    ByteBuf hb = ctx.alloc().buffer(1).writeByte('.');
                    Send(hb);
                }
            }
        }
    });

    ChannelFuture f = soc.closeFuture();
    f.addListener((ChannelFutureListener) new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            is_closed = true;
            FFServer.logger.info(String.format("%s disconnected", reg_str));
        }
    });
}