@Override public void initChannel(SocketChannel ch) { ch.pipeline().addLast(new IdleStateHandler(nettyServerConfig.getChannelMaxReadIdleSeconds(), 0, 0)) .addLast(new MessageCodecHandler()); if (null != channelHandlers) { addChannelPipelineLast(ch, channelHandlers); } } });
@Override protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception { if (IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT == evt) { logger.debug("channel write timeout {}", ctx.channel()); ProxyMessage proxyMessage = new ProxyMessage(); proxyMessage.setType(ProxyMessage.TYPE_HEARTBEAT); ctx.channel().writeAndFlush(proxyMessage); } else if (IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT == evt) { logger.warn("channel read timeout {}", ctx.channel()); ctx.channel().close(); } super.channelIdle(ctx, evt); } }
@Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { destroy(); }
@Override protected void run(ChannelHandlerContext ctx) { long nextDelay = readerIdleTimeNanos; if (!reading) { nextDelay -= ticksInNanos() - lastReadTime; } if (nextDelay <= 0) { // Reader is idle - set a new timeout and notify the callback. readerIdleTimeout = schedule(ctx, this, readerIdleTimeNanos, TimeUnit.NANOSECONDS); boolean first = firstReaderIdleEvent; firstReaderIdleEvent = false; try { IdleStateEvent event = newIdleStateEvent(IdleState.READER_IDLE, first); channelIdle(ctx, event); } catch (Throwable t) { ctx.fireExceptionCaught(t); } } else { // Read occurred before the timeout - set a new timeout with shorter delay. readerIdleTimeout = schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS); } } }
@Override protected void initChannel(Channel ch) throws Exception { int heartbeatInterval = UrlUtils.getIdleTimeout(getUrl()); NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug .addLast("decoder", adapter.getDecoder()) .addLast("encoder", adapter.getEncoder()) .addLast("client-idle-handler", new IdleStateHandler(heartbeatInterval, 0, 0, MILLISECONDS)) .addLast("handler", nettyClientHandler); } });
@Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (nettyClientConfig.isUseTLS()) { if (null != sslContext) { pipeline.addFirst(defaultEventExecutorGroup, "sslHandler", sslContext.newHandler(ch.alloc())); log.info("Prepend SSL handler"); } else { log.warn("Connections are insecure as SSLContext is null!"); } } pipeline.addLast( defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(), new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), new NettyConnectManageHandler(), new NettyClientHandler()); } });
@Override protected void initChannel(Channel ch) throws Exception { if (!requestStream.accept() || !wsStream.accept()) { ch.close(); return; ChannelPipeline pipeline = ch.pipeline(); if (sslHelper.isSSL()) { ch.pipeline().addFirst("handshaker", new SslHandshakeCompletionHandler(ar -> { if (ar.succeeded()) { if (options.isUseAlpn()) { SslHandler sslHandler = pipeline.get(SslHandler.class); String protocol = sslHandler.applicationProtocol(); if ("h2".equals(protocol)) { if (options.isSni()) { SniHandler sniHandler = new SniHandler(sslHelper.serverNameMapper(vertx)); pipeline.addFirst(sniHandler); } else { SslHandler handler = new SslHandler(sslHelper.createEngine(vertx)); IdleStateHandler idle; if (options.getIdleTimeout() > 0) { pipeline.addLast("idle", idle = new IdleStateHandler(0, 0, options.getIdleTimeout(), options.getIdleTimeoutUnit())); } else { idle = null;
if (future.isSuccess() && future.isDone()) { if (LOG.isDebugEnabled()) { LOG.debug("Connected to the new channel " + future.channel().id() + " and getting ready to " + "write request."); long channelStartTime = channelHandlerContext.channel().attr(Constants.ORIGINAL_CHANNEL_START_TIME) .get(); int timeoutOfOriginalRequest = channelHandlerContext.channel() .attr(Constants.ORIGINAL_CHANNEL_TIMEOUT).get(); setChannelAttributes(channelHandlerContext, future, httpCarbonRequest, channelStartTime, timeoutOfOriginalRequest); LOG.debug("Remaining time for redirection is : " + remainingTimeForRedirection); future.channel().pipeline().addBefore(Constants.REDIRECT_HANDLER, Constants.IDLE_STATE_HANDLER, new IdleStateHandler(remainingTimeForRedirection, remainingTimeForRedirection, 0, TimeUnit.MILLISECONDS)); future.channel().write(httpRequest); channelHandlerContext.close();
private void initWebDashboardSocket(ChannelHandlerContext ctx) { var pipeline = ctx.pipeline(); //websockets specific handlers pipeline.addFirst("AChannelState", appChannelStateHandler) .addFirst("AReadTimeout", new IdleStateHandler(appIdleTimeout, 0, 0)) .addLast("WSWebSocketServerProtocolHandler", new WebSocketServerProtocolHandler(WEBSOCKET_WEB_PATH)) .addLast("WSMessageDecoder", new WSMessageDecoder(stats, holder.limits)) .addLast("WSMessageEncoder", webAppMessageEncoder) .addLast("AGetServer", getServerHandler) .addLast("ALogin", appLoginHandler) .addLast("ANotLogged", userNotLoggedHandler); pipeline.remove(ChunkedWriteHandler.class); pipeline.remove(UrlReWriterHandler.class); pipeline.remove(StaticFileHandler.class); pipeline.remove(this); if (log.isTraceEnabled()) { log.trace("Initialized web dashboard pipeline. {}", ctx.pipeline().names()); } }
protected void addTimeoutHandlers(ChannelPipeline pipeline) { pipeline.addLast(new IdleStateHandler(0, 0, idleTimeout, TimeUnit.MILLISECONDS)); pipeline.addLast(new CloseOnIdleStateHandler()); }
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 1) { return; } // 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); } }
ChannelPipeline p = ch.pipeline(); ch.config().setAutoRead(false); ch.alloc(), host, port ); p.addFirst(HANDLER_SSL, sslHandler); readTimeout.ifPresent(duration -> { if (!duration.isNegative()) { p.addLast(HANDLER_READ_TIMEOUT, new ReadTimeoutHandler(duration.toMillis(), TimeUnit.MILLISECONDS)); Duration duration = readIdleTime.get(); if (!duration.isNegative()) { p.addLast(HANDLER_IDLE_STATE, new IdleStateHandler(duration.toMillis(), duration.toMillis(), duration.toMillis(), TimeUnit.MILLISECONDS));
@Override protected void initChannel(SocketChannel c) { MessageHandler handler = new MessageHandler(connectionManager); CodecsHandler codecs = new CodecsHandler(ProtocolType.HANDSHAKE.getProtocol()); FramingHandler framing = new FramingHandler(); try { c.config().setOption(ChannelOption.IP_TOS, 0x18); } catch (ChannelException e) { // Not supported on all OSs, like Windows XP and lesser GlowServer.logger.warning("Your OS does not support type of service."); } c.pipeline() .addLast("idle_timeout", new IdleStateHandler(READ_IDLE_TIMEOUT, WRITE_IDLE_TIMEOUT, 0)) .addLast("legacy_ping", new LegacyPingHandler(connectionManager)) .addLast("encryption", NoopHandler.INSTANCE) .addLast("framing", framing) .addLast("compression", NoopHandler.INSTANCE) .addLast("codecs", codecs) .addLast("handler", handler); } }
@Override protected void initChannel(Channel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(sslContext.newHandler(ch.alloc())); pipeline.addLast(new LoggingHandler(logLevel)) ); pipeline.addLast(new IdleStateHandler( (int) serverConfiguration.getReadIdleTimeout().getSeconds(), (int) serverConfiguration.getWriteIdleTimeout().getSeconds(),
@Override protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception { channelIdleTriggered(ctx, evt); // Close the channel. ChannelPipelineFinalizerHandler.channelInactive(...) will ensure that content is released. ctx.channel().close(); super.channelIdle(ctx, evt); }
private void configureFrameHandlingPipeline(int idleTimeout, WebSocketInboundFrameHandler frameHandler) { ChannelPipeline pipeline = ctx.pipeline(); pipeline.remove(Constants.WEBSOCKET_SERVER_HANDSHAKE_HANDLER); pipeline.remove(Constants.HTTP_CHUNK_WRITER); if (pipeline.get(UriAndHeaderLengthValidator.class) == null) { pipeline.remove(UriAndHeaderLengthValidator.class); } if (pipeline.get(MaxEntityBodyValidator.class) != null) { pipeline.remove(MaxEntityBodyValidator.class); } if (idleTimeout > 0) { pipeline.replace(Constants.IDLE_STATE_HANDLER, Constants.IDLE_STATE_HANDLER, new IdleStateHandler(0, 0, idleTimeout, TimeUnit.MILLISECONDS)); } else { pipeline.remove(Constants.IDLE_STATE_HANDLER); } pipeline.addLast(Constants.WEBSOCKET_FRAME_HANDLER, frameHandler); frameHandler.getWebSocketConnection().stopReadingFrames(); pipeline.fireChannelActive(); }
public void setEndPointTimeout(int socketIdleTimeout) { ChannelPipeline pipeline = this.getChannel().pipeline(); IdleStateHandler idleStateHandler = new IdleStateHandler(0, 0, socketIdleTimeout, TimeUnit.MILLISECONDS); if (pipeline.get(Constants.TARGET_HANDLER) == null) { pipeline.addLast(Constants.IDLE_STATE_HANDLER, idleStateHandler); } else { pipeline.addBefore(Constants.TARGET_HANDLER, Constants.IDLE_STATE_HANDLER, idleStateHandler); } http2ClientChannel.setSocketIdleTimeout(socketIdleTimeout); }
private static void parseHardwareInfo(Holder holder, ChannelHandlerContext ctx, String[] messageParts, HardwareStateHolder state, int msgId) { HardwareInfo hardwareInfo = new HardwareInfo(messageParts); int newHardwareInterval = hardwareInfo.heartbeatInterval; log.trace("Info command. heartbeat interval {}", newHardwareInterval); OTAManager otaManager = holder.otaManager; int hardwareIdleTimeout = holder.limits.hardwareIdleTimeout; //no need to change IdleStateHandler if heartbeat interval wasn't changed or wasn't provided if (hardwareIdleTimeout != 0 && newHardwareInterval > 0 && newHardwareInterval != hardwareIdleTimeout) { int newReadTimeout = NumberUtil.calcHeartbeatTimeout(newHardwareInterval); log.debug("Changing read timeout interval to {}", newReadTimeout); ctx.pipeline().replace(IdleStateHandler.class, "H_IdleStateHandler_Replaced", new IdleStateHandler(newReadTimeout, 0, 0)); } DashBoard dashBoard = state.dash; Device device = state.device; if (device != null) { otaManager.initiateHardwareUpdate(ctx, state.userKey, hardwareInfo, dashBoard, device); device.hardwareInfo = hardwareInfo; dashBoard.updatedAt = System.currentTimeMillis(); } ctx.writeAndFlush(ok(msgId), ctx.voidPromise()); }
public class MyChannelInitializer extends ChannelInitializer<Channel> { @Override public void initChannel(Channel channel) { channel.pipeline().addLast("idleStateHandler", new IdleStateHandler(60, 30, 0)); channel.pipeline().addLast("myHandler", new MyHandler()); } } // Handler should handle the IdleStateEvent triggered by IdleStateHandler. public class MyHandler extends ChannelHandlerAdapter { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; if (e.state() == IdleState.READER_IDLE) { ctx.close(); } else if (e.state() == IdleState.WRITER_IDLE) { ctx.writeAndFlush(new PingMessage()); } } } }
protected void releaseHandlers(PooledConnection conn) { final ChannelPipeline pipeline = conn.getChannel().pipeline(); removeHandlerFromPipeline(OriginResponseReceiver.CHANNEL_HANDLER_NAME, pipeline); pipeline.addAfter(PassportStateHttpClientHandler.PASSPORT_STATE_HTTP_CLIENT_HANDLER_NAME, IDLE_STATE_HANDLER_NAME, new IdleStateHandler(0, 0, connPoolConfig.getIdleTimeout(), TimeUnit.MILLISECONDS)); }