`

Netty 文件下载例子

 
阅读更多
package bhz.netty.httpfile;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author Administrator
 *访问路径:http://localhost:8765/sources/
 */
public class HttpFileServer {

    private static final String DEFAULT_URL = "/sources/";

    public void run(final int port, final String url) throws Exception {
    	EventLoopGroup bossGroup = new NioEventLoopGroup();
    	EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
		    ServerBootstrap b = new ServerBootstrap();
		    b.group(bossGroup, workerGroup)
			    .channel(NioServerSocketChannel.class)
			    .childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch)
					throws Exception {
					// 加入http的解码器
				    ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
				    // 加入ObjectAggregator解码器,作用是他会把多个消息转换为单一的FullHttpRequest或者FullHttpResponse
				    ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
				    // 加入http的编码器
				    ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
				    // 加入chunked 主要作用是支持异步发送的码流(大文件传输),但不专用过多的内存,防止java内存溢出
				    ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
				    // 加入自定义处理文件服务器的业务逻辑handler
				    ch.pipeline().addLast("fileServerHandler",
					    new HttpFileServerHandler(url));
				}
			    });
		    ChannelFuture future = b.bind("127.0.0.1", port).sync();
		    System.out.println("HTTP文件目录服务器启动,网址是 : " + "http://localhost:"  + port + url);
		    future.channel().closeFuture().sync();
		} finally {
		    bossGroup.shutdownGracefully();
		    workerGroup.shutdownGracefully();
		}
    }

    public static void main(String[] args) throws Exception {
		int port = 8765;
		String url = DEFAULT_URL;
		new HttpFileServer().run(port, url);
    }
}

 

package bhz.netty.httpfile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

import bhz.utils.HttpCallerUtils;
import bhz.utils.HttpProxy;

public class Test {

	
	public static void main(String[] args) throws Exception{
		Map<String, String> params = new HashMap<String, String>();
		byte[] ret = HttpCallerUtils.getStream("http://127.0.0.1:8765/sources/a.doc", params);
		
		//byte[] ret = HttpProxy.get("http://192.168.1.111:8765/images/006.jpg");
        //写出文件
        String writePath = System.getProperty("user.dir") + File.separatorChar + "receive" +  File.separatorChar + "a.doc";
        FileOutputStream fos = new FileOutputStream(writePath);
        fos.write(ret);
        fos.close();    
		
		
	}
}

 

package bhz.netty.httpfile;

import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpMethod.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;
import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static io.netty.handler.codec.http.HttpResponseStatus.FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpResponseStatus.METHOD_NOT_ALLOWED;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelProgressiveFuture;
import io.netty.channel.ChannelProgressiveFutureListener;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderUtil;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.stream.ChunkedFile;
import io.netty.util.CharsetUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Pattern;

import javax.activation.MimetypesFileTypeMap;

public class HttpFileServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    
	private final String url;

    public HttpFileServerHandler(String url) {
    	this.url = url;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    	//对请求的解码结果进行判断:
		if (!request.decoderResult().isSuccess()) {
			// 400
		    sendError(ctx, BAD_REQUEST);
		    return;
		}
		//对请求方式进行判断:如果不是get方式(如post方式)则返回异常
		if (request.method() != GET) {
			// 405
		    sendError(ctx, METHOD_NOT_ALLOWED);
		    return;
		}
		//获取请求uri路径
		final String uri = request.uri();
		//对url进行分析,返回本地系统
		final String path = sanitizeUri(uri);
		//如果 路径构造不合法,则path为null
		if (path == null) {
			//403
		    sendError(ctx, FORBIDDEN);
		    return;
		}
		// 创建file对象
		File file = new File(path);
		// 判断文件是否为隐藏或者不存在
		if (file.isHidden() || !file.exists()) {
			// 404 
		    sendError(ctx, NOT_FOUND);
		    return;
		}
		// 如果为文件夹
		if (file.isDirectory()) {
		    if (uri.endsWith("/")) {
		    	//如果以正常"/"结束 说明是访问的一个文件目录:则进行展示文件列表(web服务端则可以跳转一个Controller,遍历文件并跳转到一个页面)
		    	sendListing(ctx, file);
		    } else {
		    	//如果非"/"结束 则重定向,补全"/" 再次请求
		    	sendRedirect(ctx, uri + '/');
		    }
		    return;
		}
		// 如果所创建的file对象不是文件类型
		if (!file.isFile()) {
			// 403
		    sendError(ctx, FORBIDDEN);
		    return;
		}
		
		//随机文件读写类
		RandomAccessFile randomAccessFile = null;
		try {
		    randomAccessFile = new RandomAccessFile(file, "r");// 以只读的方式打开文件
		} catch (FileNotFoundException fnfe) {
			// 404
		    sendError(ctx, NOT_FOUND);
		    return;
		}
		
		//获取文件长度
		long fileLength = randomAccessFile.length();
		//建立响应对象
		HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
		//设置响应信息
		HttpHeaderUtil.setContentLength(response, fileLength);
		//设置响应头
		setContentTypeHeader(response, file);
		//如果一直保持连接则设置响应头信息为:HttpHeaders.Values.KEEP_ALIVE
		if (HttpHeaderUtil.isKeepAlive(request)) {
		    response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
		}
		//进行写出
		ctx.write(response);
		
		//构造发送文件线程,将文件写入到Chunked缓冲区中
		ChannelFuture sendFileFuture;
		//写出ChunkedFile
		sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), ctx.newProgressivePromise());
		//添加传输监听
		sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
		    @Override
		    public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
				if (total < 0) { // total unknown
				    System.err.println("Transfer progress: " + progress);
				} else {
				    System.err.println("Transfer progress: " + progress + " / " + total);
				}
		    }
		    @Override
		    public void operationComplete(ChannelProgressiveFuture future) throws Exception {
		    	System.out.println("Transfer complete.");
		    }
		});
		
		//如果使用Chunked编码,最后则需要发送一个编码结束的看空消息体,进行标记,表示所有消息体已经成功发送完成。
		ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
		//如果当前连接请求非Keep-Alive ,最后一包消息发送完成后 服务器主动关闭连接
		if (!HttpHeaderUtil.isKeepAlive(request)) {
		    lastContentFuture.addListener(ChannelFutureListener.CLOSE);
		}
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    	//cause.printStackTrace();
		if (ctx.channel().isActive()) {
		    sendError(ctx, INTERNAL_SERVER_ERROR);
		    ctx.close();
		}
    }

    //非法URI正则
    private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*");

    /**
     * <B>方法名称:</B>解析URI<BR>
     * <B>概要说明:</B>对URI进行分析<BR>
     * @param uri netty包装后的字符串对象
     * @return path 解析结果
     */
    private String sanitizeUri(String uri) {
		try {
			//使用UTF-8字符集
		    uri = URLDecoder.decode(uri, "UTF-8");
		} catch (UnsupportedEncodingException e) {
		    try {
		    	//尝试ISO-8859-1
		    	uri = URLDecoder.decode(uri, "ISO-8859-1");
		    } catch (UnsupportedEncodingException e1) {
		    	//抛出预想外异常信息
		    	throw new Error();
		    }
		}
		// 对uri进行细粒度判断:4步验证操作
		// step 1 基础验证
		if (!uri.startsWith(url)) {
		    return null;
		}
		// step 2 基础验证
		if (!uri.startsWith("/")) {
		    return null;
		}
		// step 3 将文件分隔符替换为本地操作系统的文件路径分隔符
		uri = uri.replace('/', File.separatorChar);
		// step 4 二次验证合法性
		if (uri.contains(File.separator + '.')
			|| uri.contains('.' + File.separator) || uri.startsWith(".")
			|| uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()) {
		    return null;
		}
		//当前工程所在目录 + URI构造绝对路径进行返回 
		return System.getProperty("user.dir") + File.separator + uri;
    }
    
    //文件是否被允许访问下载验证
    private static final Pattern ALLOWED_FILE_NAME = Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*");

    private static void sendListing(ChannelHandlerContext ctx, File dir) {
    	// 设置响应对象
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
		// 响应头
		response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
		// 追加文本内容
		StringBuilder ret = new StringBuilder();
		String dirPath = dir.getPath();
		ret.append("<!DOCTYPE html>\r\n");
		ret.append("<html><head><title>");
		ret.append(dirPath);
		ret.append(" 目录:");
		ret.append("</title></head><body>\r\n");
		ret.append("<h3>");
		ret.append(dirPath).append(" 目录:");
		ret.append("</h3>\r\n");
		ret.append("<ul>");
		ret.append("<li>链接:<a href=\"../\">..</a></li>\r\n");
		
		// 遍历文件 添加超链接
		for (File f : dir.listFiles()) {
			//step 1: 跳过隐藏或不可读文件 
		    if (f.isHidden() || !f.canRead()) {
		    	continue;
		    }
		    String name = f.getName();
		    //step 2: 如果不被允许,则跳过此文件
		    if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
		    	continue;
		    }
		    //拼接超链接即可
		    ret.append("<li>链接:<a href=\"");
		    ret.append(name);
		    ret.append("\">");
		    ret.append(name);
		    ret.append("</a></li>\r\n");
		}
		ret.append("</ul></body></html>\r\n");
		//构造结构,写入缓冲区
		ByteBuf buffer = Unpooled.copiedBuffer(ret, CharsetUtil.UTF_8);
		//进行写出操作
		response.content().writeBytes(buffer);
		//重置写出区域
		buffer.release();
		//使用ctx对象写出并且刷新到SocketChannel中去 并主动关闭连接(这里是指关闭处理发送数据的线程连接)
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    //重定向操作
    private static void sendRedirect(ChannelHandlerContext ctx, String newUri) {
    	//建立响应对象
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND);
		//设置新的请求地址放入响应对象中去
		response.headers().set(LOCATION, newUri);
		//使用ctx对象写出并且刷新到SocketChannel中去 并主动关闭连接(这里是指关闭处理发送数据的线程连接)
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    //错误信息
    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    	//建立响应对象
    	FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString()+ "\r\n", CharsetUtil.UTF_8));
    	//设置响应头信息
    	response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    	//使用ctx对象写出并且刷新到SocketChannel中去 并主动关闭连接(这里是指关闭处理发送数据的线程连接)
    	ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static void setContentTypeHeader(HttpResponse response, File file) {
    	//使用mime对象获取文件类型
    	MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    	response.headers().set(CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
    }
}

 

分享到:
评论

相关推荐

    netty4.0源码,netty例子,netty api文档

    包含javadoc,jar 两个文件夹。 doc中是文档资料。 jar是源码及常用例子,均好源码,好使。

    用netty实现文件传输

    简单但是内容不浅的netty传输文件的例子,实现客户端和服务器端。全面,5积分绝对值得。本人通过很久测试才完成该简单通俗易懂的例子。 netty版本:4.0.23

    netty http协议开发小例子

    本代码用一个文件服务器为背景,用netty写的http协议开发例子。希望大家有所帮助。

    netty4完整配置及实例

    由于netty各个版本之间差异较大,这里整理了一下各个版本的包及样例,使用了maven工程,将各个版本需要的最简jar文件已配置完全,可以在些基础上进行正式项目的开发。

    netty入门例子--(不是翻译官方文档)

    基于netty-3.2.7.Final写了几个开发模板 有助于了解消息异步通讯机制,tcp通讯的封装. java此类模板还有 mina . 后续会把项目中mina模板抽出来供大家参考.

    netty基于protobuf的简单示例

    写了一个简单的netty server和client,传输协议是google protobuf。上传文件主要包括源码以及转换proto文件的工具.

    netty4分片上传文件

    netty4分片上传文件的小例子,使用编码LengthFieldBasedFramDecoder控制服务器一次性可接收超过1024个字节

    netty-3.7.0官方API所有jar包

    netty-3.7.0官方1).API文档 2).所有jar包 3).example使用例子

    SwiftNIO-NettyExamples:SwiftNIO中Netty示例的实现

    用SwiftNIO实现的Netty例子 看过SwiftNIO文档的朋友想必都见过这样的一句话: 就像Netty,但是是为Swift写的。 SwiftNIO和Netty的关系非常近,其开发团队的核心人员Netty的主要开发者。SwiftNIO也直接采用了Netty...

    netty in action

    第五版netty英文文档,通俗易懂,例子非常多

    Netty-SpringMVC:SpringMVC文件配置化

    Netty-SpringMVC 是一个netty、SpingMVC集成是例子。这种框架主要应用于SOA的架构中充当服务提供者, 用传统的springMVC+web容器也...此例子下载到本地可以运行org.kurt.netty.Main 然后浏览器访问127.0.0.1:8070/test

    netty-framework

    netty-framework 两个概念:IOC/DI 和AOP IOC:Inversion of Control,控制反转,不创建对象,但是描述创建它们的方式。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。容器负责将...

    SSH2整合完整的例子(包含jar包)

    一个小例子,很适合初学者学习SSH2,对struts2.0+spring+Hibernate整合的一个用户管理的增删改查及分页的例子。 其中只要修改src.com.user.cfg配置文件下applicationContext-common.xml这个里面的oralce驱动,...

    Java NIO 中文全书签

    这本书是介绍java nio的基础书籍,原理讲的还是挺明白的,比较好懂,就是例子比较少。nio对于java程序员来说可能不是很好理解,但是对于C程序员来说,就是epoll的一个封装。 我本人是C程序员,对java比较感兴趣,...

    JAVA上百实例源码以及开源项目

    1个目标文件,JNDI的使用例子,有源代码,可以下载参考,JNDI的使用,初始化Context,它是连接JNDI树的起始点,查找你要的对象,打印找到的对象,关闭Context…… ftp文件传输 2个目标文件,FTP的目标是:(1)提高...

    webSocket4xmpp:这是webSocket通过xmpp子协议调用openfire的例子

    我使用jetty通过http和Netty提供静态文件,以处理webRTC通信。 此示例基于khs-stockticker: 使用的技术: Http服务器的码头WebSocket服务器的净额GSON用于JSON数据Maven构建工具 操作说明: 打开控制台并执行...

    spring-boot示例项目

    netty|[基于BIO、NIO等tcp服务器搭建介绍](https://github.com/smltq/spring-boot-demo/blob/master/netty) ### Spring Cloud 模块 模块名称|主要内容 ---|--- cloud-oauth2-auth-code|[基于spring cloud...

    leetcode分类-Java-grammar1:java学习资料,使用技巧,各方面应用,基于jdk1.8.151版本之前的总结,各个版本更改

    更新java,简单netty例子 2018.08.12 更新设计模式 行为模式 命令模式 状态模式 观察者模式 中介者模式 2018.08.09 更新设计模式 结构型模式 适配器模式 桥接模式, 装饰模式, 外观模式, 享元模式, 代理模式。...

    JAVA上百实例源码以及开源项目源代码

    EJB中JNDI的使用源码例子 1个目标文件,JNDI的使用例子,有源代码,可以下载参考,JNDI的使用,初始化Context,它是连接JNDI树的起始点,查找你要的对象,打印找到的对象,关闭Context…… ftp文件传输 2个目标文件...

Global site tag (gtag.js) - Google Analytics