通过SocketChannel高速传输期间的数据丢失

时间:2014-11-06 21:29:45

标签: java android networking nio socketchannel

我正在开发Android应用程序,手机在Wifi-Direct上执行某些计算。 在我看来,效率至关重要。我的协议的瓶颈是一个网络。我使用SocketChannel来接收/传输数据。 这是我的伪代码:

byte[] array = new byte[]{20,20,20,20,20,20,20,20,20,20};
        for (int i=0; i<10; i++)
        {
            ByteBuffer sendBB = ByteBuffer.allocate(buffSize);
            sendBB.put(array, 0, array.length);
            sendBB.rewind();
            ByteBuffer receiveBB = ByteBuffer.allocate(buffSize);

            try {

                socketChannel.read(receiveBB);
                socketChannel.write(sendBB);

                byte[] received = new byte[10];
                receiveBB.rewind();
                receiveBB.get(received, 0, 10);
                Log.i("Received", Arrays.toString(received));           


            } catch (IOException e) {
                e.printStackTrace();
            }
        }

类似的代码适用于其他方。 连接创建如下:

serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(socketAddress);           
socketChannel = serverSocketChannel.accept();

事实证明,当buffSize很小时,一切都传得很好:100,200。 当它是500或更高时,我有数据丢失。我收到的内容如下:

[20,20,20,20,20,20,20,20,20,20]
[0,0,0,0,0,0,0,0,0,0]
[20,20,20,20,20,20,20,20,20,20]
[20,20,20,20,20,20,20,20,20,20]
[0,0,0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,0,0,0]
[20,20,20,20,20,20,20,20,20,20]
[20,20,20,20,20,20,20,20,20,20]
[20,20,20,20,20,20,20,20,20,20]
[20,20,20,20,20,20,20,20,20,20]

更高的缓冲区让速度更快。有没有办法,如何保持速度并防止数据丢失? 谢谢

2 个答案:

答案 0 :(得分:0)

常见问题。

socketChannel.read(receiveBB);
socketChannel.write(sendBB);

您忽略了read()write()返回的长度。

byte[] received = new byte[10];
receiveBB.rewind();
receiveBB.get(received, 0, 10);

这都错了。它应该是:

int count = socketChannel.read(receiveBB);
byte[] received = new byte[count];
receiveBB.flip();
receiveBB.get(received);
receiveBB.compact();

如果你期望固定长度的消息,你必须循环,直到你得到它们。 read()没有义务填补缓冲区。

答案 1 :(得分:0)

通过循环读写来解决问题:

int countWritten=0;
while (countWritten < buffSize)
{
    countWritten+=socketChannel.write(sendBB);
}