2012-01-11 44 views
0

我通過Netty服務器(圖像,html)從Android資產提供文件。 文本文件,一個HTML保存爲MP3播放禁用壓縮(我需要一個InputStream!)用Netty服務文件 - 響應被截斷一個字節

我的管道正在尋找這樣的:

pipeline.addLast("decoder", new HttpRequestDecoder()); 
    pipeline.addLast("aggregator", new HttpChunkAggregator(65536)); 
    pipeline.addLast("encoder", new HttpResponseEncoder()); 
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); 

    pipeline.addLast("handler", new AssetsServerHandler(context)); 

我的處理程序是:

public class AssetsServerHandler extends SimpleChannelUpstreamHandler { 

    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { 

     // some checks 

     final FileInputStream is; 
     final AssetFileDescriptor afd; 
     try { 
      afd = assetManager.openFd(path); 
      is = afd.createInputStream(); 
     } catch(IOException exc) { 
      sendError(ctx, NOT_FOUND); 
      return; 
     } 

     final long fileLength = afd.getLength(); 

     HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); 
     setContentLength(response, fileLength); 

     final Channel ch = e.getChannel(); 
     final ChannelFuture future; 
     ch.write(response); 
     future = ch.write(new ChunkedStream(is)); 
     future.addListener(new ChannelFutureListener() { 
      @Override 
      public void operationComplete(ChannelFuture future) throws Exception { 
       future.getChannel().close(); 
      } 
     }); 
     if (!isKeepAlive(request)) { 
      future.addListener(ChannelFutureListener.CLOSE); 
     } 
    } 
    // other stuff 
} 

使用該處理程序,我的截取至少有一個字節。如果我將ChunkedStream更改爲ChunkedNioFile(因此使用is.getChannel()而不是is作爲它的構造函數) - 一切正常。

請幫我理解ChunkedStream有什麼問題。

回答

1

你的代碼看起來很適合我。 AssetFileDescriptor的返回FileInputStream是否包含「所有字節」?你可以用單元測試來檢查它。如果它沒有錯誤,那麼它是一個netty中的錯誤。我大量使用ChunkInputStream,並且從來沒有遇到過這樣的問題,但也許它確實取決於InputStream的本質。

如果你可以寫一個測試用例並在netty的github上打開一個問題,那會很好。

+0

我使用的'FileInputStream'是在Android核心的某處產生的。那麼我如何進行單元測試呢?我認爲它比Netty更適合Android。順便說一句,'Channel'我從這個(相同的!)'FileInputStream'中工作正常。 – Olegas 2012-01-12 14:16:13

+1

我會寫一個單元測試,將一個字節序列寫入一個文件。然後用AssetFileDescriptor打開文件,獲取FileInputStream並從中讀取所有字節。然後檢查每個字節,如果它等於您之前寫入文件的字節。你應該測試這個不同的FileInputStream.read(...)方法... – 2012-01-13 07:07:37

+0

好主意,我會嘗試它。謝謝。 – Olegas 2012-01-14 07:50:50