/** * Writes response metadata to the channel if not already written previously and channel is * active. * * @param responseMetadata the {@link HttpResponse} that needs to be written. * @param listener the {@link GenericFutureListener} that needs to be attached to the write. * @return {@code true} if response metadata was written to the channel in this call. {@code * false} otherwise. */ private boolean maybeWriteResponseMetadata( HttpResponse responseMetadata, GenericFutureListener<ChannelFuture> listener) { long writeProcessingStartTime = System.currentTimeMillis(); boolean writtenThisTime = false; if (responseMetadataWritten.compareAndSet(false, true)) { // we do some manipulation here for chunking. According to the HTTP spec, we can have either a // Content-Length // or Transfer-Encoding:chunked, never both. So we check for Content-Length - if it is not // there, we add // Transfer-Encoding:chunked. Note that sending HttpContent chunks data anyway - we are just // explicitly specifying // this in the header. if (!HttpHeaders.isContentLengthSet(responseMetadata)) { // This makes sure that we don't stomp on any existing transfer-encoding. HttpHeaders.setTransferEncodingChunked(responseMetadata); } logger.trace( "Sending response with status {} on channel {}", responseMetadata.getStatus(), ctx.channel()); ChannelPromise writePromise = ctx.newPromise().addListener(listener); ctx.writeAndFlush(responseMetadata, writePromise); writtenThisTime = true; long writeProcessingTime = System.currentTimeMillis() - writeProcessingStartTime; nettyMetrics.responseMetadataProcessingTimeInMs.update(writeProcessingTime); } return writtenThisTime; }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("================进入客户端InBoundHandler channelRead============"); // 如果是response if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; logger.debug( "客户端收到的响应CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE)); if (HttpHeaders.isContentLengthSet(response)) { reader = new ByteBufToBytes((int) HttpHeaders.getContentLength(response)); } } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); reader.reading(content); content.release(); if (reader.isEnd()) { String resultStr = new String(reader.readFull()); logger.debug("收到的服务端的消息是:" + resultStr); ctx.close(); } } logger.debug("================出客户端InBoundHandler channelRead============"); }