`
jayghost
  • 浏览: 429446 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Netty文件传输,使用HttpChunk

    博客分类:
  • Java
阅读更多

利用Netty中提供的HttpChunk简单实现文件传输

服务端基本和Netty官方文档中的example:http--file一样。

客户端:

HttpClient:

public class HttpClient {
	private ClientBootstrap bootstrap;
	private String host="localhost";
	private Channel channel;
	private boolean futureSuccess;
	private int port=8080;

	public HttpClient() {
	}

	public ChannelFuture connect() {
		bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors
				.newCachedThreadPool()));
		HttpResponseHandler clientHandler = new HttpResponseHandler();
		bootstrap.setPipelineFactory(new HttpClientPipelineFactory(clientHandler));

		bootstrap.setOption("tcpNoDelay", true);
		bootstrap.setOption("keepAlive", true);

		return bootstrap.connect(new InetSocketAddress(host,port));
	}
	
	public boolean checkFutureState(ChannelFuture channelFuture) {
		// Wait until the connection attempt succeeds or fails.
		channel = channelFuture.awaitUninterruptibly().getChannel();
		channelFuture.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture connectFuture) throws Exception {
				if (!connectFuture.isSuccess()) {
					connectFuture.getCause().printStackTrace();
					// connectFuture.getChannel().close();
					// bootstrap.releaseExternalResources();
					futureSuccess = false;
				} else {
					futureSuccess = true;
				}
			}
		});
		return futureSuccess;
	}
	
	public ChannelFuture write(HttpRequest request) {
		return channel.write(request);
	}
	
	public void Close() {
		// Close the connection. Make sure the close operation ends because
		// all I/O operations are asynchronous in Netty.
		channel.close().awaitUninterruptibly();
		// Shut down all thread pools to exit.
		bootstrap.releaseExternalResources();
	}
}

 HttpClientPipelineFactory:

public class HttpClientPipelineFactory implements ChannelPipelineFactory {
	private final HttpResponseHandler handler;

	public HttpClientPipelineFactory(HttpResponseHandler handler) {
		this.handler = handler;
	}
	
	public ChannelPipeline getPipeline() throws Exception {
		ChannelPipeline pipeline = pipeline();
		
        pipeline.addLast("decoder", new HttpResponseDecoder());
        //pipeline.addLast("aggregator", new HttpChunkAggregator(6048576));
        pipeline.addLast("encoder", new HttpRequestEncoder());
        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
        pipeline.addLast("handler", handler);
        
        return pipeline;
	}
}

HttpResponseHandler:

@ChannelPipelineCoverage("one")
public class HttpResponseHandler extends SimpleChannelUpstreamHandler {
	private volatile boolean readingChunks;
	private File downloadFile;
	private FileOutputStream fOutputStream = null;

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		if (e.getMessage() instanceof HttpResponse) {
			DefaultHttpResponse httpResponse = (DefaultHttpResponse) e.getMessage();
			String fileName = httpResponse.getHeader("Content-Disposition").substring(20);
			downloadFile = new File(System.getProperty("user.dir") + File.separator + "download" + fileName);
			readingChunks = httpResponse.isChunked();
		} else {
			HttpChunk httpChunk = (HttpChunk) e.getMessage();
			if (!httpChunk.isLast()) {
				ChannelBuffer buffer = httpChunk.getContent();
				if (fOutputStream == null) {
					fOutputStream = new FileOutputStream(downloadFile);
				}
				while (buffer.readable()) {
					byte[] dst = new byte[buffer.readableBytes()];
					buffer.readBytes(dst);
					fOutputStream.write(dst);
				}
			} else {
				readingChunks = false;
			}
			fOutputStream.flush();
		}
		if (!readingChunks) {
			fOutputStream.close();
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		System.out.println(e.getCause());
	}
}

  main:

public class ClientMain {
	public static void main(String[] args) {
		HttpClient httpClient=new HttpClient();
		ChannelFuture connectFuture=httpClient.connect();
		if (httpClient.checkFutureState(connectFuture)) {
			System.out.println("connect ok");
			HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "thunder.zip");
//			HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "thunder.java");
			ChannelFuture writeFuture= httpClient.write(request);
			if (httpClient.checkFutureState(writeFuture)) {
				System.out.println("write ok");
			}
		}
	}
}

 

改天看看零拷贝方式

 

 

 

分享到:
评论

相关推荐

    netty文件传输服务端与客户端以及协议说明

    通用的netty传输协议 通过该协议进行文件传输 文件传输客户端与服务端 可以根据文件的最后更新时间来增量传输文件 源码开放,通过eclipse或者idea导入代码即可运行 协议开放,协议是自定义的协议,大家可以根据需求...

    用netty实现文件传输

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

    Netty 文件上传获取进度条

    通过netty获取文件进度,上传文件的时时数据大小,剩余时间.websocket和HTML结合,并不javascript的轮询获取上传进度,而是通过NIO的推送.

    NETTY 分布式文件传输

    封装NETTY来实现一个分布式文件传输服务,目标是提供定时的可靠安全文件传输。同时提供一种简便的方式,只需将数据配置好

    Netty+H5实现实时进度条文件上传,支持断点续传

    Netty+H5实现实时进度条文件上传,支持断点续传。 1、WebSocketServer:服务启动类 2、服务启动后,浏览器访问http://localhost:9999 3、FileWebSocketFrameHandler类SERVER_SAVE_PATH常量为文件上传保存路经

    netty-codec-http-4.1.27.Final-API文档-中英对照版.zip

    赠送Maven依赖信息文件:netty-codec-http-4.1.27.Final.pom; 包含翻译后的API文档:netty-codec-http-4.1.27.Final-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:io.netty:netty-codec-...

    netty-codec-http-4.1.11.Final-API文档-中文版.zip

    赠送Maven依赖信息文件:netty-codec-http-4.1.11.Final.pom; 包含翻译后的API文档:netty-codec-http-4.1.11.Final-javadoc-API文档-中文(简体)版.zip; Maven坐标:io.netty:netty-codec-http:4.1.11.Final; ...

    netty-codec-http2-4.1.74.Final-API文档-中文版.zip

    赠送Maven依赖信息文件:netty-codec-http2-4.1.74.Final.pom; 包含翻译后的API文档:netty-codec-http2-4.1.74.Final-javadoc-API文档-中文(简体)版.zip; Maven坐标:io.netty:netty-codec-http2:4.1.74.Final; ...

    Netty5多文件、大文件上传源码

    支持多文件、大文件上传,客户端长连接,只要客户端有文件就通知服务器要发送文件。

    netty-codec-http-4.1.73.Final-API文档-中文版.zip

    赠送Maven依赖信息文件:netty-codec-http-4.1.73.Final.pom; 包含翻译后的API文档:netty-codec-http-4.1.73.Final-javadoc-API文档-中文(简体)版.zip; Maven坐标:io.netty:netty-codec-http:4.1.73.Final; ...

    reactor-netty-http-1.0.11-API文档-中文版.zip

    赠送Maven依赖信息文件:reactor-netty-http-1.0.11.pom; 包含翻译后的API文档:reactor-netty-http-1.0.11-javadoc-API文档-中文(简体)版.zip; Maven坐标:io.projectreactor.netty:reactor-netty-http:1.0.11; ...

    使用netty5进行udp网络通讯

    这个小程序使用netty5进行udp网络通讯,客户端有两种,1:用netty5类库发送DatagramPacket和接收 2:直接使用DatagramSocket发送接收DatagramPacket 先运行netty_server的QuoteOfTheMomentServer, 在运行netty_...

    netty-codec-http2-4.1.73.Final-API文档-中文版.zip

    赠送Maven依赖信息文件:netty-codec-http2-4.1.73.Final.pom; 包含翻译后的API文档:netty-codec-http2-4.1.73.Final-javadoc-API文档-中文(简体)版.zip; Maven坐标:io.netty:netty-codec-http2:4.1.73.Final; ...

    netty-codec-http-4.1.74.Final-API文档-中文版.zip

    赠送Maven依赖信息文件:netty-codec-http-4.1.74.Final.pom; 包含翻译后的API文档:netty-codec-http-4.1.74.Final-javadoc-API文档-中文(简体)版.zip; Maven坐标:io.netty:netty-codec-http:4.1.74.Final; ...

    netty-codec-http-4.1.11.Final-API文档-中英对照版.zip

    赠送Maven依赖信息文件:netty-codec-http-4.1.11.Final.pom; 包含翻译后的API文档:netty-codec-http-4.1.11.Final-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:io.netty:netty-codec-...

    netty4.0文件分片上传+断点续传+权限校验

    描述文档请看我的个人博客:www.mesoftware.cn

    netty file server 文件服务

    netty file server 文件服务 实现 列表 上传 下载

    netty学习文件,实现http,websocket,protobuf

    netty学习文件,实现http,websocket,protobuf方式,实现服务器与客户端通信。

    netty文件传输

    包括netty的文件传输的实例,以及一些netty的简单的实例,里面包含有相对应的jar包,比起那些要5分,然后下下来P都没有的要实惠多了。自己也是新研究的,希望能和大家一起讨论分享

    netty-codec-http2-4.1.73.Final-API文档-中英对照版.zip

    赠送Maven依赖信息文件:netty-codec-http2-4.1.73.Final.pom; 包含翻译后的API文档:netty-codec-http2-4.1.73.Final-javadoc-API文档-中文(简体)-英语-对照版.zip; Maven坐标:io.netty:netty-codec-...

Global site tag (gtag.js) - Google Analytics