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
我相信问题是需要回拨方法调用。我重构了我的听众以执行以下操作,并且我相信它现在正在工作: byteBuffer.rewind(); channel.read(byteBuffer); byteBuffer.rewind(); foc.write(byteBuffer); – azdragon2 2012-01-26 22:42:00