Netty文件传输,使用HttpChunk

97 篇文章 1 订阅
Java代码   收藏代码
  1. public class HttpClient {  
  2.   
  3.     private ClientBootstrap bootstrap;  
  4.     private String host="localhost";  
  5.     private Channel channel;  
  6.     private boolean futureSuccess;  
  7.     private int port=8080;  
  8.   
  9.     public HttpClient() {  
  10.     }  
  11.   
  12.     public ChannelFuture connect() {  
  13.         bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors  
  14.                 .newCachedThreadPool()));  
  15.         HttpResponseHandler clientHandler = new HttpResponseHandler();  
  16.         bootstrap.setPipelineFactory(new HttpClientPipelineFactory(clientHandler));  
  17.   
  18.         bootstrap.setOption("tcpNoDelay"true);  
  19.         bootstrap.setOption("keepAlive"true);  
  20.   
  21.         return bootstrap.connect(new InetSocketAddress(host,port));  
  22.     }  
  23.       
  24.     public boolean checkFutureState(ChannelFuture channelFuture) {  
  25.         // Wait until the connection attempt succeeds or fails.  
  26.         channel = channelFuture.awaitUninterruptibly().getChannel();  
  27.         channelFuture.addListener(new ChannelFutureListener() {  
  28.             @Override  
  29.             public void operationComplete(ChannelFuture connectFuture) throws Exception {  
  30.                 if (!connectFuture.isSuccess()) {  
  31.                     connectFuture.getCause().printStackTrace();  
  32.                     // connectFuture.getChannel().close();  
  33.                     // bootstrap.releaseExternalResources();  
  34.                     futureSuccess = false;  
  35.                 } else {  
  36.                     futureSuccess = true;  
  37.                 }  
  38.             }  
  39.         });  
  40.         return futureSuccess;  
  41.     }  
  42.       
  43.     public ChannelFuture write(HttpRequest request) {  
  44.         return channel.write(request);  
  45.     }  
  46.       
  47.     public void Close() {  
  48.         // Close the connection. Make sure the close operation ends because  
  49.         // all I/O operations are asynchronous in Netty.  
  50.         channel.close().awaitUninterruptibly();  
  51.         // Shut down all thread pools to exit.  
  52.         bootstrap.releaseExternalResources();  
  53.     }  
  54. }  
Java代码   收藏代码
  1. public class HttpClientPipelineFactory implements ChannelPipelineFactory {    
  2.     private final HttpResponseHandler handler;    
  3.     
  4.     public HttpClientPipelineFactory(HttpResponseHandler handler) {    
  5.         this.handler = handler;    
  6.     }    
  7.         
  8.     public ChannelPipeline getPipeline() throws Exception {    
  9.         ChannelPipeline pipeline = pipeline();    
  10.             
  11.         pipeline.addLast("decoder"new HttpResponseDecoder());    
  12.         //pipeline.addLast("aggregator", new HttpChunkAggregator(6048576));    
  13.         pipeline.addLast("encoder"new HttpRequestEncoder());    
  14.         pipeline.addLast("chunkedWriter"new ChunkedWriteHandler());    
  15.         pipeline.addLast("handler", handler);    
  16.             
  17.         return pipeline;    
  18.     }    
  19. }    
Java代码   收藏代码
  1. @ChannelPipelineCoverage("one")    
  2. public class HttpResponseHandler extends SimpleChannelUpstreamHandler {    
  3.     private volatile boolean readingChunks;    
  4.     private File downloadFile;    
  5.     private FileOutputStream fOutputStream = null;    
  6.     
  7.     @Override    
  8.     public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {    
  9.         if (e.getMessage() instanceof HttpResponse) {    
  10.             DefaultHttpResponse httpResponse = (DefaultHttpResponse) e.getMessage();    
  11.             String fileName = httpResponse.getHeader("Content-Disposition").substring(20);    
  12.             downloadFile = new File(System.getProperty("user.dir") + File.separator + "download" + fileName);    
  13.             readingChunks = httpResponse.isChunked();    
  14.         } else {    
  15.             HttpChunk httpChunk = (HttpChunk) e.getMessage();    
  16.             if (!httpChunk.isLast()) {    
  17.                 ChannelBuffer buffer = httpChunk.getContent();    
  18.                 if (fOutputStream == null) {    
  19.                     fOutputStream = new FileOutputStream(downloadFile);    
  20.                 }    
  21.                 while (buffer.readable()) {    
  22.                     byte[] dst = new byte[buffer.readableBytes()];    
  23.                     buffer.readBytes(dst);    
  24.                     fOutputStream.write(dst);    
  25.                 }    
  26.             } else {    
  27.                 readingChunks = false;    
  28.             }    
  29.             fOutputStream.flush();    
  30.         }    
  31.         if (!readingChunks) {    
  32.             fOutputStream.close();    
  33.         }    
  34.     }    
  35.     
  36.     @Override    
  37.     public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {    
  38.         System.out.println(e.getCause());    
  39.     }    
  40. }    
Java代码   收藏代码
  1. public class ClientMain {    
  2.     public static void main(String[] args) {    
  3.         HttpClient httpClient=new HttpClient();    
  4.         ChannelFuture connectFuture=httpClient.connect();    
  5.         if (httpClient.checkFutureState(connectFuture)) {    
  6.             System.out.println("connect ok");    
  7.             HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "thunder.zip");    
  8. //          HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "thunder.java");    
  9.             ChannelFuture writeFuture= httpClient.write(request);    
  10.             if (httpClient.checkFutureState(writeFuture)) {    
  11.                 System.out.println("write ok");    
  12.             }    
  13.         }    
  14.     }    
  15. }    
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值