Android VPN服务Bytebuffer无法写入

问题描述 投票:0回答:1

我正在开发一个带有VPN服务的数据包嗅探器Android应用程序但我在读取从Fileinputstream到bytebuffer的数据包时遇到了麻烦。问题是每次我将数据包写入bytebuffer时,它都没有bytebuffer中的任何数据。请帮帮我。谢谢

 FileInputStream in = new FileInputStream(traffic_interface.getFileDescriptor());

                FileOutputStream out = new FileOutputStream(traffic_interface.getFileDescriptor());
                DatagramChannel tunnel = DatagramChannel.open();
                if (!protect(tunnel.socket())) {throw new IllegalStateException("Cannot protect the tunnel");}

                tunnel.connect((new InetSocketAddress("127.0.0.1",0)));
                tunnel.configureBlocking(false);
                int n = 0;

                while (!Thread.interrupted()){
                    packet = ByteBuffer.allocate(65535);

                    int packet_length = in.read(packet.array());
                    Log.d("UDPinStream","UDP:" +packet_length);

                    if(packet_length != -1 && packet_length > 0){
                        Log.d("UDPinStream","UDP:" + packet_length);
                        Log.d("UDPinStream","packet:" + packet);

                        packet.clear();
                    }

该问题占用以下代码

                int packet_length = in.read(packet.array());

                if(packet_length != -1 && packet_length > 0){
                    Log.d("UDPinStream","UDP:" + packet_length);
                    Log.d("UDPinStream","packet:" + packet);

                    packet.clear();
                }

虽然它成功地从隧道中读取了数据包(packet_length> 0),但是字节缓冲区的pos中也没有数据在Bytebuffer数据包中没有变化。 java.nio.HeapByteBuffer [pos = 0 lim = 65535 cap = 65535]

java android fileinputstream bytebuffer
1个回答
0
投票

ByteBuffers旨在与频道一起使用。您应该使用通道的任何读/写(ByteBuffer buf)接口来正确使用ByteBuffers。

无论如何,在你的片段中,read()获取byte [],写入它但ByteBuffer不知道它的后备数组被填充。所以,你可以这样做,

if (packet_length != -1 && packet_length > 0) {
    packet.position(packet_length);  // filled till that pos
    packet.flip();                   // No more writes, make it ready for reading

   // Do read from packet buffer
   // then, packet.clear() or packet.compact() to read again.
}

请继续关注NIO / ByteBuffer示例。

© www.soinside.com 2019 - 2024. All rights reserved.