Search in sources :

Example 86 with Channel

use of io.netty.channel.Channel in project async-http-client by AsyncHttpClient.

the class NettyConnectListener method onSuccess.

public void onSuccess(Channel channel, InetSocketAddress remoteAddress) {
    if (connectionSemaphore != null) {
        // transfer lock from future to channel
        Object partitionKeyLock = future.takePartitionKeyLock();
        if (partitionKeyLock != null) {
            channel.closeFuture().addListener(future -> connectionSemaphore.releaseChannelLock(partitionKeyLock));
        }
    }
    Channels.setActiveToken(channel);
    TimeoutsHolder timeoutsHolder = future.getTimeoutsHolder();
    if (futureIsAlreadyCancelled(channel)) {
        return;
    }
    Request request = future.getTargetRequest();
    Uri uri = request.getUri();
    timeoutsHolder.setResolvedRemoteAddress(remoteAddress);
    ProxyServer proxyServer = future.getProxyServer();
    // in case of proxy tunneling, we'll add the SslHandler later, after the CONNECT request
    if ((proxyServer == null || proxyServer.getProxyType().isSocks()) && uri.isSecured()) {
        SslHandler sslHandler;
        try {
            sslHandler = channelManager.addSslHandler(channel.pipeline(), uri, request.getVirtualHost(), proxyServer != null);
        } catch (Exception sslError) {
            onFailure(channel, sslError);
            return;
        }
        final AsyncHandler<?> asyncHandler = future.getAsyncHandler();
        try {
            asyncHandler.onTlsHandshakeAttempt();
        } catch (Exception e) {
            LOGGER.error("onTlsHandshakeAttempt crashed", e);
            onFailure(channel, e);
            return;
        }
        sslHandler.handshakeFuture().addListener(new SimpleFutureListener<Channel>() {

            @Override
            protected void onSuccess(Channel value) {
                try {
                    asyncHandler.onTlsHandshakeSuccess();
                } catch (Exception e) {
                    LOGGER.error("onTlsHandshakeSuccess crashed", e);
                    NettyConnectListener.this.onFailure(channel, e);
                    return;
                }
                writeRequest(channel);
            }

            @Override
            protected void onFailure(Throwable cause) {
                try {
                    asyncHandler.onTlsHandshakeFailure(cause);
                } catch (Exception e) {
                    LOGGER.error("onTlsHandshakeFailure crashed", e);
                    NettyConnectListener.this.onFailure(channel, e);
                    return;
                }
                NettyConnectListener.this.onFailure(channel, cause);
            }
        });
    } else {
        writeRequest(channel);
    }
}
Also used : Channel(io.netty.channel.Channel) HttpRequest(io.netty.handler.codec.http.HttpRequest) Request(org.asynchttpclient.Request) Uri(org.asynchttpclient.uri.Uri) SslHandler(io.netty.handler.ssl.SslHandler) ConnectException(java.net.ConnectException) TimeoutsHolder(org.asynchttpclient.netty.timeout.TimeoutsHolder) ProxyServer(org.asynchttpclient.proxy.ProxyServer)

Example 87 with Channel

use of io.netty.channel.Channel in project async-http-client by AsyncHttpClient.

the class AsyncHttpClientHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel channel = ctx.channel();
    Object attribute = Channels.getAttribute(channel);
    try {
        if (attribute instanceof OnLastHttpContentCallback && msg instanceof LastHttpContent) {
            ((OnLastHttpContentCallback) attribute).call();
        } else if (attribute instanceof NettyResponseFuture) {
            NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
            future.touch();
            handleRead(channel, future, msg);
        } else if (attribute instanceof StreamedResponsePublisher) {
            StreamedResponsePublisher publisher = (StreamedResponsePublisher) attribute;
            publisher.future().touch();
            if (msg instanceof HttpContent) {
                ByteBuf content = ((HttpContent) msg).content();
                // Republish as a HttpResponseBodyPart
                if (content.isReadable()) {
                    HttpResponseBodyPart part = config.getResponseBodyPartFactory().newResponseBodyPart(content, false);
                    ctx.fireChannelRead(part);
                }
                if (msg instanceof LastHttpContent) {
                    // Remove the handler from the pipeline, this will trigger
                    // it to finish
                    ctx.pipeline().remove(publisher);
                    // Trigger a read, just in case the last read complete
                    // triggered no new read
                    ctx.read();
                    // Send the last content on to the protocol, so that it can
                    // conclude the cleanup
                    handleRead(channel, publisher.future(), msg);
                }
            } else {
                logger.info("Received unexpected message while expecting a chunk: " + msg);
                ctx.pipeline().remove(publisher);
                Channels.setDiscard(channel);
            }
        } else if (attribute != DiscardEvent.DISCARD) {
            // unhandled message
            logger.debug("Orphan channel {} with attribute {} received message {}, closing", channel, attribute, msg);
            Channels.silentlyCloseChannel(channel);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
Also used : Channel(io.netty.channel.Channel) OnLastHttpContentCallback(org.asynchttpclient.netty.OnLastHttpContentCallback) NettyResponseFuture(org.asynchttpclient.netty.NettyResponseFuture) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ByteBuf(io.netty.buffer.ByteBuf) HttpContent(io.netty.handler.codec.http.HttpContent) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpResponseBodyPart(org.asynchttpclient.HttpResponseBodyPart)

Example 88 with Channel

use of io.netty.channel.Channel in project async-http-client by AsyncHttpClient.

the class AsyncHttpClientHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
    Throwable cause = getCause(e);
    if (cause instanceof PrematureChannelClosureException || cause instanceof ClosedChannelException)
        return;
    Channel channel = ctx.channel();
    NettyResponseFuture<?> future = null;
    logger.debug("Unexpected I/O exception on channel {}", channel, cause);
    try {
        Object attribute = Channels.getAttribute(channel);
        if (attribute instanceof StreamedResponsePublisher) {
            ctx.fireExceptionCaught(e);
            // setting `attribute` to be the underlying future so that the
            // retry logic can kick-in
            attribute = ((StreamedResponsePublisher) attribute).future();
        }
        if (attribute instanceof NettyResponseFuture<?>) {
            future = (NettyResponseFuture<?>) attribute;
            future.attachChannel(null, false);
            future.touch();
            if (cause instanceof IOException) {
                // FIXME why drop the original exception and throw a new one?
                if (hasIOExceptionFilters) {
                    if (!requestSender.applyIoExceptionFiltersAndReplayRequest(future, ChannelClosedException.INSTANCE, channel)) {
                        // Close the channel so the recovering can occurs.
                        Channels.silentlyCloseChannel(channel);
                    }
                    return;
                }
            }
            if (StackTraceInspector.recoverOnReadOrWriteException(cause)) {
                logger.debug("Trying to recover from dead Channel: {}", channel);
                future.pendingException = cause;
                return;
            }
        } else if (attribute instanceof OnLastHttpContentCallback) {
            future = OnLastHttpContentCallback.class.cast(attribute).future();
        }
    } catch (Throwable t) {
        cause = t;
    }
    if (future != null)
        try {
            logger.debug("Was unable to recover Future: {}", future);
            requestSender.abort(channel, future, cause);
            handleException(future, e);
        } catch (Throwable t) {
            logger.error(t.getMessage(), t);
        }
    channelManager.closeChannel(channel);
    // FIXME not really sure
    // ctx.fireChannelRead(e);
    Channels.silentlyCloseChannel(channel);
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) Channel(io.netty.channel.Channel) OnLastHttpContentCallback(org.asynchttpclient.netty.OnLastHttpContentCallback) NettyResponseFuture(org.asynchttpclient.netty.NettyResponseFuture) PrematureChannelClosureException(io.netty.handler.codec.PrematureChannelClosureException) IOException(java.io.IOException)

Example 89 with Channel

use of io.netty.channel.Channel in project swift by luastar.

the class HttpServer method start.

public void start() {
    // 设置线程名称
    ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
    EventLoopGroup bossGroup = new NioEventLoopGroup(HttpConstant.SWIFT_BOSS_THREADS, threadFactoryBuilder.setNameFormat("boss-group-%d").build());
    EventLoopGroup workerGroup = new NioEventLoopGroup(HttpConstant.SWIFT_WORKER_THREADS, threadFactoryBuilder.setNameFormat("worker-group-%d").build());
    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (ssl) {
                    SelfSignedCertificate ssc = new SelfSignedCertificate();
                    SslContext sslContext = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
                    pipeline.addLast(sslContext.newHandler(ch.alloc()));
                }
                // 超时处理
                pipeline.addLast(new IdleStateHandler(0, 0, HttpConstant.SWIFT_TIMEOUT));
                // http request decode and response encode
                pipeline.addLast(new HttpServerCodec());
                // 将消息头和体聚合成FullHttpRequest和FullHttpResponse
                pipeline.addLast(new HttpObjectAggregator(HttpConstant.SWIFT_MAX_CONTENT_LENGTH));
                // 压缩处理
                pipeline.addLast(new HttpContentCompressor(HttpConstant.SWIFT_COMPRESSION_LEVEL));
                // 自定义http服务
                pipeline.addLast(new HttpChannelHandler(handlerMapping));
            }
        });
        Channel channel = bootstrap.bind(port).sync().channel();
        channel.closeFuture().sync();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) HttpContentCompressor(io.netty.handler.codec.http.HttpContentCompressor) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 90 with Channel

use of io.netty.channel.Channel in project dubbo by alibaba.

the class NettyClient method doOpen.

@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    final NettyClientHandler nettyClientHandler = new NettyClientHandler(getUrl(), this);
    bootstrap = new Bootstrap();
    bootstrap.group(nioEventLoopGroup).option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).channel(NioSocketChannel.class);
    if (getTimeout() < 3000) {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000);
    } else {
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    }
    bootstrap.handler(new ChannelInitializer() {

        protected void initChannel(Channel ch) throws Exception {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            // .addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
            ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("encoder", adapter.getEncoder()).addLast("handler", nettyClientHandler);
        }
    });
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) RemotingException(com.alibaba.dubbo.remoting.RemotingException)

Aggregations

Channel (io.netty.channel.Channel)884 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)226 ChannelFuture (io.netty.channel.ChannelFuture)204 Test (org.junit.Test)203 Bootstrap (io.netty.bootstrap.Bootstrap)199 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)191 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)177 InetSocketAddress (java.net.InetSocketAddress)165 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)151 EventLoopGroup (io.netty.channel.EventLoopGroup)142 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)138 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)132 IOException (java.io.IOException)126 ByteBuf (io.netty.buffer.ByteBuf)112 SocketChannel (io.netty.channel.socket.SocketChannel)106 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)99 ChannelPipeline (io.netty.channel.ChannelPipeline)98 CountDownLatch (java.util.concurrent.CountDownLatch)96 LocalChannel (io.netty.channel.local.LocalChannel)93 LocalServerChannel (io.netty.channel.local.LocalServerChannel)89