Android NIO Channel byteBuffer在接收器上为空

时间:2012-01-26 22:14:19

标签: android nio channel bytebuffer

我遇到了一个问题,我在我的Android设备上打开一个本地文件,而我正试图将它发送到另一个正在侦听端口的设备上。它正在发送信息(我在mappedByteBuffer中看到数据)。但是,当在侦听器上收到数据并且我查看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

1 个答案:

答案 0 :(得分:0)

找到以这种方式写入频道的最佳方式如下(不要使用我原来的方式,它会产生缺少的字符和额外的空格):

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

byteBuffer.flip();  
while (byteBuffer.hasRemaining()) 
{  
    foc.write(byteBuffer);  
}