2012-01-26 121 views
0

我遇到了一個問題,即我在Android設備上打開本地文件,並試圖將其發送到另一個端口上偵聽的設備。它發送信息(我在mappedByteBuffer中看到數據)。但是,當偵聽器接收到數據並查看byteBuffer時,數據全部爲空。有人能指出我做錯了什麼嗎?謝謝!Android NIO通道byteBuffer在接收器上爲空

發件人:

WritableByteChannel channel; 
FileChannel fic; 
long fsize; 
ByteBuffer byteBuffer; 
MappedByteBuffer mappedByteBuffer; 

connection = new Socket(Resource.LAN_IP_ADDRESS, Resource.LAN_SOCKET_PORT); 
out = connection.getOutputStream(); 
File f = new File(filename); 

in = new FileInputStream(f); 
fic = in.getChannel(); 
fsize = fic.size(); 
channel = Channels.newChannel(out); 

//other code  

//Send file 
long currPos = 0; 
while (currPos < fsize) 
{ 
    if (fsize - currPos < Resource.MEMORY_ALLOC_SIZE) 
    {      
     mappedByteBuffer = fic.map(FileChannel.MapMode.READ_ONLY, currPos, fsize - currPos); 
     channel.write(mappedByteBuffer); 
     currPos = fsize; 
    } 
    else 
    { 
     mappedByteBuffer = fic.map(FileChannel.MapMode.READ_ONLY, currPos, Resource.MEMORY_ALLOC_SIZE); 
     channel.write(mappedByteBuffer); 
     currPos += Resource.MEMORY_ALLOC_SIZE; 
    } 
} 

closeAllConnections(); //closes connection, fic, channel, in, out 

監聽

FileChannel foc; 
ByteBuffer byteBuffer; 
ReadableByteChannel channel; 

serverSoc = new ServerSocket(myPort); 
connection = serverSoc.accept(); 
connection.setSoTimeout(3600000); 
connection.setReceiveBufferSize(Resource.MEMORY_ALLOC_SIZE); 
in = connection.getInputStream(); 
out = new FileOutputStream(new File(currentFileName)); 
foc = out.getChannel(); 
channel = Channels.newChannel(in); 

//other code   

while (fileSize > 0) 
{ 
    if (fileSize < Resource.MEMORY_ALLOC_SIZE) 
    { 
     byteBuffer = ByteBuffer.allocate((int)fileSize); 
     channel.read(byteBuffer); 
     //byteBuffer is blank! 
     foc.write(byteBuffer); 
     fileSize = 0; 
    } 
    else 
    { 
     byteBuffer = ByteBuffer.allocate(Resource.MEMORY_ALLOC_SIZE); 
     channel.read(byteBuffer); 
     //byteBuffer is blank!       
     foc.write(byteBuffer); 
     fileSize -= Resource.MEMORY_ALLOC_SIZE; 
    } 
} 

closeAllConnections(); //closes connection, foc, channel, in, out, serverSoc 

注: MEMORY_ALLOC_SIZE = 32768

+0

我相信問題是需要回撥方法調用。我重構了我的聽衆以執行以下操作,並且我相信它現在正在工作: byteBuffer.rewind(); channel.read(byteBuffer); byteBuffer.rewind(); foc.write(byteBuffer); – azdragon2 2012-01-26 22:42:00

回答

0

找到寫信給渠道的最佳方式這種方式是跟隨着克(不要用我原來的方式,它會產生缺少的字符和額外的空格):

while (channel.read(byteBuffer) != -1) 
{ 
    byteBuffer.flip(); 
    foc.write(byteBuffer); 
    byteBuffer.compact(); 
} 

byteBuffer.flip(); 
while (byteBuffer.hasRemaining()) 
{ 
    foc.write(byteBuffer); 
} 
相關問題