io.netty.handler.stream.ChunkedNioFile Java Examples

The following examples show how to use io.netty.handler.stream.ChunkedNioFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NettyOutbound.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * Sends content from the given {@link Path} using
 * {@link java.nio.channels.FileChannel#transferTo(long, long, WritableByteChannel)}
 * support, if the system supports it, the path resolves to a local file
 * system {@link File}, compression and SSL/TLS is not enabled, then transfer will
 * use zero-byte copy to the peer., otherwise chunked read/write will be used.
 * <p>It will listens for any error on write and closes
 * on terminal signal (complete|error). If more than one publisher is attached
 * (multiple calls to send()) completion occurs after all publishers complete.</p>
 * <p></p>Note: Nesting any send* method is not supported.</p>
 *
 * @param file the file Path
 * @param position where to start
 * @param count how much to transfer
 *
 * @return A Publisher to signal successful sequence write (e.g. after "flush") or any
 * error during write
 */
default NettyOutbound sendFile(Path file, long position, long count) {
	Objects.requireNonNull(file, "filepath");

	return sendUsing(() -> FileChannel.open(file, StandardOpenOption.READ),
			(c, fc) -> {
				if (ReactorNetty.mustChunkFileTransfer(c, file)) {
					ReactorNetty.addChunkedWriter(c);
					try {
						return new ChunkedNioFile(fc, position, count, 1024);
					}
					catch (Exception ioe) {
						throw Exceptions.propagate(ioe);
					}
				}
				return new DefaultFileRegion(fc, position, count);
			},
			ReactorNetty.fileCloser);
}
 
Example #2
Source File: NettyOutbound.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
/**
 * Sends content from given {@link Path} using chunked read/write. <p>It will listen
 * for any error on write and close on terminal signal (complete|error). If more than
 * one publisher is attached (multiple calls to send()) completion occurs after all
 * publishers complete.</p>
 * <p>Note: Nesting any send* method is not supported.</p>
 *
 * @param file the file Path
 * @param position where to start
 * @param count how much to transfer
 *
 * @return A Publisher to signal successful sequence write (e.g. after "flush") or any
 * error during write
 */
default NettyOutbound sendFileChunked(Path file, long position, long count) {
	Objects.requireNonNull(file, "filepath");

	return sendUsing(() -> FileChannel.open(file, StandardOpenOption.READ),
			(c, fc) -> {
				ReactorNetty.addChunkedWriter(c);
				try {
					return new ChunkedNioFile(fc, position, count, 1024);
				}
				catch (Exception e) {
					throw Exceptions.propagate(e);
				}
			},
			ReactorNetty.fileCloser);
}
 
Example #3
Source File: HttpRequestHandle.java    From netty-learning with MIT License 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    if (wsUri.equalsIgnoreCase(request.getUri())) {
        //如果是 websocket 请求则交给下一个 channelHandler 处理
        ctx.fireChannelRead(request.retain());
    } else {

        //读取 index.html
        RandomAccessFile file = new RandomAccessFile(INDEX, "r");
        DefaultHttpResponse response = new DefaultHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
        response.headers().set("Content-Type", "text/html; charset=UTF-8");

        //是 keepAlive 则添加对应的头信息
        boolean keepAlive = HttpHeaders.isKeepAlive(request);
        if (keepAlive) {
            response.headers().set("Content-Length", file.length());
            response.headers().set("Connection", "keep-alive");
        }
        //将 Response 写回客户端
        ctx.write(response);

        //将 index.html 写回客户端
        if (ctx.pipeline().get(SslHandler.class) == null) {
            //没有加密
            ctx.write(new DefaultFileRegion(file.getChannel(), 0, file.length()));
        }else {
            ctx.write(new ChunkedNioFile(file.getChannel())) ;
        }

        //写 LastHttpContent 写回客户端
        ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

        if (!keepAlive){
            //没有 keepAlive 就断开连接
            future.addListener(ChannelFutureListener.CLOSE) ;
        }
    }
}
 
Example #4
Source File: EchoServerHttpRequestHandler.java    From examples-javafx-repos1 with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
	
	if( wsURI.equalsIgnoreCase(request.getUri()) ) {
		
		ctx.fireChannelRead(request.retain());
	
	} else {
		
		if( HttpHeaders.is100ContinueExpected(request) ) {
			send100Continue(ctx);
		}
		
		try (
			RandomAccessFile rFile = new RandomAccessFile(indexHTML, "r")
		) {
			HttpResponse response = new DefaultHttpResponse( request.getProtocolVersion(), HttpResponseStatus.OK );
			response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
			boolean keepAlive = HttpHeaders.isKeepAlive(request);
			if( keepAlive ) {
				response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, rFile.length());
				response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
			}
			
			ctx.write(response);
			
			if( ctx.pipeline().get(SslHandler.class) == null ) {
				ctx.write(new DefaultFileRegion(rFile.getChannel(), 0, rFile.length()));
			} else {
				ctx.write(new ChunkedNioFile(rFile.getChannel()));
			}
			
			ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
			
			if( !keepAlive ) {
				future.addListener(ChannelFutureListener.CLOSE);
			}
		}
	}
}
 
Example #5
Source File: HttpChunkedInputTest.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Test
public void testChunkedNioFile() throws IOException {
    check(new HttpChunkedInput(new ChunkedNioFile(TMP)));
}
 
Example #6
Source File: HttpRequestHandler.java    From java-tutorial with MIT License 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (wsUri.equalsIgnoreCase(request.uri())) {
        //如果请求是一次升级了的 WebSocket 请求
        //则递增引用计数器(retain)并且将它传递给在 ChannelPipeline 中的下个 ChannelInboundHandler
        ctx.fireChannelRead(request.retain());
    } else {
        if (HttpUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }
        //读取 webchat.html
        RandomAccessFile file = new RandomAccessFile(INDEX, "r");

        HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8");

        //判断 keepalive 是否在请求头里面
        boolean keepAlive = HttpUtil.isKeepAlive(request);
        if (keepAlive) {
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, file.length());
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        //写 HttpResponse 到客户端
        ctx.write(response);

        //根据 ChannelPipeline 中是否有 SslHandler 来决定使用 DefaultFileRegion 还是 ChunkedNioFile
        if (ctx.pipeline().get(SslHandler.class) == null) {
            ctx.write(new DefaultFileRegion(file.getChannel(), 0, file.length()));
        } else {
            ctx.write(new ChunkedNioFile(file.getChannel()));
        }
        //写并刷新 LastHttpContent 到客户端,标记响应完成
        ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (!keepAlive) {
            //请求头中不包含 keepalive,当写完成时,关闭 Channel
            future.addListener(ChannelFutureListener.CLOSE);
        }

        file.close();
    }
}
 
Example #7
Source File: HttpChunkedInputTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@Test
public void testChunkedNioFile() throws IOException {
    check(new HttpChunkedInput(new ChunkedNioFile(TMP)));
}