Search in sources :

Example 1 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project spring-framework by spring-projects.

the class Netty4ClientHttpRequestFactory method buildBootstrap.

private Bootstrap buildBootstrap(URI uri, boolean isSecure) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            configureChannel(channel.config());
            ChannelPipeline pipeline = channel.pipeline();
            if (isSecure) {
                Assert.notNull(sslContext, "sslContext should not be null");
                pipeline.addLast(sslContext.newHandler(channel.alloc(), uri.getHost(), uri.getPort()));
            }
            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(maxResponseSize));
            if (readTimeout > 0) {
                pipeline.addLast(new ReadTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
            }
        }
    });
    return bootstrap;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) Bootstrap(io.netty.bootstrap.Bootstrap) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 2 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project camel by apache.

the class NettyProducer method processWithConnectedChannel.

public void processWithConnectedChannel(final Exchange exchange, final BodyReleaseCallback callback, final ChannelFuture channelFuture, final Object body) {
    // remember channel so we can reuse it
    final Channel channel = channelFuture.channel();
    if (getConfiguration().isReuseChannel() && exchange.getProperty(NettyConstants.NETTY_CHANNEL) == null) {
        exchange.setProperty(NettyConstants.NETTY_CHANNEL, channel);
        // and defer closing the channel until we are done routing the exchange
        exchange.addOnCompletion(new SynchronizationAdapter() {

            @Override
            public void onComplete(Exchange exchange) {
                // should channel be closed after complete?
                Boolean close;
                if (ExchangeHelper.isOutCapable(exchange)) {
                    close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                } else {
                    close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                }
                // should we disconnect, the header can override the configuration
                boolean disconnect = getConfiguration().isDisconnect();
                if (close != null) {
                    disconnect = close;
                }
                if (disconnect) {
                    LOG.trace("Closing channel {} as routing the Exchange is done", channel);
                    NettyHelper.close(channel);
                }
                releaseChannel(channelFuture);
            }
        });
    }
    if (exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT) != null) {
        long timeoutInMs = exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT, Long.class);
        ChannelHandler oldHandler = channel.pipeline().get("timeout");
        ReadTimeoutHandler newHandler = new ReadTimeoutHandler(timeoutInMs, TimeUnit.MILLISECONDS);
        if (oldHandler == null) {
            channel.pipeline().addBefore("handler", "timeout", newHandler);
        } else {
            channel.pipeline().replace(oldHandler, "timeout", newHandler);
        }
    }
    //This will refer to original callback since netty will release body by itself
    final AsyncCallback producerCallback;
    if (configuration.isReuseChannel()) {
        // use callback as-is because we should not put it back in the pool as NettyProducerCallback would do
        // as when reuse channel is enabled it will put the channel back in the pool when exchange is done using on completion
        producerCallback = callback.getOriginalCallback();
    } else {
        producerCallback = new NettyProducerCallback(channelFuture, callback.getOriginalCallback());
    }
    // setup state as attachment on the channel, so we can access the state later when needed
    putState(channel, new NettyCamelState(producerCallback, exchange));
    // here we need to setup the remote address information here
    InetSocketAddress remoteAddress = null;
    if (!isTcp()) {
        remoteAddress = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    }
    // write body
    NettyHelper.writeBodyAsync(LOG, channel, remoteAddress, body, exchange, new ChannelFutureListener() {

        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            LOG.trace("Operation complete {}", channelFuture);
            if (!channelFuture.isSuccess()) {
                // no success then exit, (any exception has been handled by ClientChannelHandler#exceptionCaught)
                return;
            }
            // if we do not expect any reply then signal callback to continue routing
            if (!configuration.isSync()) {
                try {
                    // should channel be closed after complete?
                    Boolean close;
                    if (ExchangeHelper.isOutCapable(exchange)) {
                        close = exchange.getOut().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                    } else {
                        close = exchange.getIn().getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
                    }
                    // should we disconnect, the header can override the configuration
                    boolean disconnect = getConfiguration().isDisconnect();
                    if (close != null) {
                        disconnect = close;
                    }
                    // we should not close if we are reusing the channel
                    if (!configuration.isReuseChannel() && disconnect) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Closing channel when complete at address: {}", getEndpoint().getConfiguration().getAddress());
                        }
                        NettyHelper.close(channel);
                    }
                } finally {
                    // signal callback to continue routing
                    producerCallback.done(false);
                }
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollDatagramChannel(io.netty.channel.epoll.EpollDatagramChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) AsyncCallback(org.apache.camel.AsyncCallback) ChannelHandler(io.netty.channel.ChannelHandler) ChannelFutureListener(io.netty.channel.ChannelFutureListener) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ConnectException(java.net.ConnectException) CamelExchangeException(org.apache.camel.CamelExchangeException) Exchange(org.apache.camel.Exchange) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 3 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project herddb by diennea.

the class NettyConnector method connect.

public static NettyChannel connect(String host, int port, boolean ssl, int connectTimeout, int socketTimeout, ChannelEventListener receiver, final ExecutorService callbackExecutor, final MultithreadEventLoopGroup networkGroup, final DefaultEventLoopGroup localEventsGroup) throws IOException {
    try {
        final SslContext sslCtx = !ssl ? null : SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        Class<? extends Channel> channelType;
        InetSocketAddress inet = new InetSocketAddress(host, port);
        SocketAddress address;
        String hostAddress = NetworkUtils.getAddress(inet);
        MultithreadEventLoopGroup group;
        if (LocalServerRegistry.isLocalServer(hostAddress, port, ssl)) {
            channelType = LocalChannel.class;
            address = new LocalAddress(hostAddress + ":" + port + ":" + ssl);
            group = localEventsGroup;
        } else {
            channelType = networkGroup instanceof EpollEventLoopGroup ? EpollSocketChannel.class : NioSocketChannel.class;
            address = inet;
            group = networkGroup;
        }
        Bootstrap b = new Bootstrap();
        AtomicReference<NettyChannel> result = new AtomicReference<>();
        b.group(group).channel(channelType).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout).handler(new ChannelInitializer<Channel>() {

            @Override
            public void initChannel(Channel ch) throws Exception {
                NettyChannel channel = new NettyChannel(host + ":" + port, ch, callbackExecutor);
                result.set(channel);
                channel.setMessagesReceiver(receiver);
                if (ssl) {
                    ch.pipeline().addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                if (socketTimeout > 0) {
                    ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(socketTimeout));
                }
                ch.pipeline().addLast("lengthprepender", new LengthFieldPrepender(4));
                ch.pipeline().addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                // 
                ch.pipeline().addLast("messageencoder", new DataMessageEncoder());
                ch.pipeline().addLast("messagedecoder", new DataMessageDecoder());
                ch.pipeline().addLast(new InboundMessageHandler(channel));
            }
        });
        LOGGER.log(Level.FINE, "connecting to {0}:{1} ssl={2} address={3}", new Object[] { host, port, ssl, address });
        b.connect(address).sync();
        return result.get();
    } catch (InterruptedException ex) {
        throw new IOException(ex);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) MultithreadEventLoopGroup(io.netty.channel.MultithreadEventLoopGroup) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext) LocalAddress(io.netty.channel.local.LocalAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler)

Example 4 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project apiRecord by tobecoder2015.

the class NettyHttpProxyServer method start.

public void start(int port) {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // ChannelInboundHandlerAdapter
    try {
        init();
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast("httpCodec", new HttpServerCodec());
                ch.pipeline().addLast(new ReadTimeoutHandler(10));
                ch.pipeline().addLast(new WriteTimeoutHandler(10));
                ch.pipeline().addLast("serverHandle", new HttpProxyServerHandle(proxyInterceptFactory.build()));
            }
        });
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) WriteTimeoutHandler(io.netty.handler.timeout.WriteTimeoutHandler) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpProxyServerHandle(com.wing.apirecord.core.handler.HttpProxyServerHandle) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 5 with ReadTimeoutHandler

use of io.netty.handler.timeout.ReadTimeoutHandler in project jdepth by Crab2died.

the class C2DServer method bind.

private void bind(String host, int port) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new C2DHessianMsgDecoder(1024 * 1024, 4, 4, -8, 0)).addLast("MessageEncoder", new C2DHessianMsgEncoder()).addLast("ReadTimeoutHandler", new ReadTimeoutHandler(TIME_OUT)).addLast("LoginAuthResp", new LoginAuthRespHandler()).addLast("Pong", new PongHandler());
            }
        });
        ChannelFuture future = bootstrap.bind(host, port).sync();
        future.channel().closeFuture().sync();
        logger.info("server is started");
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PongHandler(com.github.jvm.io.protocol.c2d.heart.PongHandler) C2DHessianMsgDecoder(com.github.jvm.io.protocol.c2d.codc.hessian.C2DHessianMsgDecoder) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) C2DHessianMsgEncoder(com.github.jvm.io.protocol.c2d.codc.hessian.C2DHessianMsgEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) LoginAuthRespHandler(com.github.jvm.io.protocol.c2d.auth.LoginAuthRespHandler) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

ReadTimeoutHandler (io.netty.handler.timeout.ReadTimeoutHandler)18 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)7 ChannelPipeline (io.netty.channel.ChannelPipeline)6 Bootstrap (io.netty.bootstrap.Bootstrap)5 SocketChannel (io.netty.channel.socket.SocketChannel)5 ChannelHandler (io.netty.channel.ChannelHandler)4 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 Channel (io.netty.channel.Channel)3 ChannelFuture (io.netty.channel.ChannelFuture)3 EpollSocketChannel (io.netty.channel.epoll.EpollSocketChannel)3 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)3 SslContext (io.netty.handler.ssl.SslContext)3 SslHandler (io.netty.handler.ssl.SslHandler)3 IOException (java.io.IOException)3 InetSocketAddress (java.net.InetSocketAddress)3 C2DHessianMsgDecoder (com.github.jvm.io.protocol.c2d.codc.hessian.C2DHessianMsgDecoder)2 C2DHessianMsgEncoder (com.github.jvm.io.protocol.c2d.codc.hessian.C2DHessianMsgEncoder)2 EventLoopGroup (io.netty.channel.EventLoopGroup)2