Java流的字节。读操作有时不会读取所写的内容

时间:2015-02-21 00:09:51

标签: java stream byte inputstream outputstream

我正在尝试使用自动重复请求策略来实现通信系统。我使用三个类:发射器,通道,接收器。我有一个最大字节数的消息(窗口)。但是当我收到发送的字节时,有时我收到的字节少于窗口。为什么? 我的代码是这样的:

发射机

int n = 0;
int remaining, length;
while (n<channelBytes.length) {
     remaining = channelBytes.length-n;
     length = (remaining<window)? remaining : window;
     outputStream.write(channelBytes,n,length);
     // wait for the ack
     byte[] b = new byte[4];
     channel.socket().setSoTimeout(2000);
     inputStream.read(b);
     n += ByteBuffer.wrap(b).getInt();
}

频道

bytes = new byte[SystemModel.WINDOW];
while(true) {
    // receive from Tx
    upInputStream.read(bytes);
    // insert channel error
    insertError(bytes);
    Thread.sleep(propagationDelay + transmissionDelay);
    // send bytes to Rx
    downOutputStream.write(bytes);
    // wait for the ack from Rx
    clientChannelDown.socket().setSoTimeout(2000);
    byte[] ack = new byte[4];
    downInputStream.read(ack);
    // send ack to Tx
    upOutputStream.write(ByteBuffer.allocate(4).put(ack).array());
}

接收机

byte[] b = new byte[SystemModel.WINDOW];
while (true) {
    try {
        int received = inputStream.read(b);
        channelCoding.decodePartially(b);                                        
    }catch (SocketTimeoutException te){  
        break;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DataFormatException e) {
        // send ack
        int ack = Integer.parseInt(e.getMessage());
        try {
            outputStream.write(ByteBuffer.allocate(4).putInt(ack).array());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

在Receiver中,字节数组“b”并不总是窗口的长度。

1 个答案:

答案 0 :(得分:1)

无效的代码。见Javadoc。 InputStream.read(byte[] [,...])没有义务传输多个字节,并且在不将结果存储到变量中的情况下调用它是永远无效的。如果您期望多个字节,则必须循环或使用DataInputStream.readFully().

在Java中复制流的规范方法如下:

while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

对于ByteBuffers Channels,如下所示:

while (in.read(buffer) > 0 || buffer.position() > 0)
{
    buffer.flip();
    out.write(buffer);
    buffer.compact();
}

如果您正确编码,则无需在网络代码中插入睡眠。

E&安培; OE