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

前端之家收集整理的这篇文章主要介绍了利用Netty中提供的HttpChunk简单实现文件传输前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

  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. }

  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. }

  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. }

  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,"thunder.java");
  9. ChannelFuture writeFuture= httpClient.write(request);
  10. if (httpClient.checkFutureState(writeFuture)) {
  11. System.out.println("write ok");
  12. }
  13. }
  14. }
  15. }

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

猜你在找的netty相关文章