简体   繁体   English

ByteArrayOutputStream:奇怪的行为

[英]ByteArrayOutputStream: Odd behavior

I'm writing a simple client-server application and I wanted to be able to take the attributes of a Header class, turn them into a byte[], send them to the other host, and then convert them back into an easily parsed Header. 我正在编写一个简单的客户端-服务器应用程序,并且希望能够采用Header类的属性,将它们转换为byte [],将其发送到其他主机,然后将它们转换回易于解析的Header 。 I was using a ByteArrayOutputStream to do this, but the results were not what I expected. 我正在使用ByteArrayOutputStream来执行此操作,但是结果不是我期望的。 For example, just to test it in main() I had: 例如,仅为了在main()中进行测试,我就拥有:

Header h = Header();
h.setSource(111);
h.setDest(222);
h.setSeq(333);
h.setAck(444);
byte[] header = Header.convertHeaderToByteArray();
Header newHeader = new Header(headerArray);

Where convertHeaderToByteArray() looked like: 其中convertHeaderToByteArray()看起来像:

public byte[] convertHeaderToByteArray() {
    byte[] headerArray;
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream(44);
    byteStream.write(srcPort);
    byteStream.write(dstPort);
    byteStream.write(seqNum);
    byteStream.write(ackNum);
    byteStream.write(controlBits);
    headerArray = byteStream.toByteArray();
    return headerArray;
}

And the Header(headerArray) constructor: 还有Header(headerArray)构造函数:

public Header(byte[] headerArray) {
    ByteArrayInputStream header = new ByteArrayInputStream(headerArray);
    srcPort = header.read();
    dstPort = header.read();
    seqNum = header.read();
    ackNum = header.read();
}

This definitely did not behave as expected. 这绝对不符合预期。 When I looked at those values at the end, srcPort was correct (111), dstPort was correct (222), seqNum was not correct (77), and ackNum was not correct (188). 当我最后查看这些值时,srcPort是正确的(111),dstPort是正确的(222),seqNum是不正确的(77),而ackNum是不正确的(188)。

After hours of reading and tinkering I couldn't get it right, so I tried to use ByteBuffer instead. 经过数小时的阅读和修改后,我无法正确完成操作,因此我尝试使用ByteBuffer代替。 Viola, correct results. 中提琴,正确的结果。

What is going on here? 这里发生了什么? I read the documentation for both and although I spotted some differences I'm not seeing what the source of my error is. 我阅读了两者的文档,尽管发现了一些差异,但我看不到错误的根源。

OutputStream.write(int) writes a single byte. OutputStream.write(int)写入一个字节。 See the Javadoc. 请参阅Javadoc。 If you want to write wider values, you will have to use the writeXXX() methods of DataOutputStream, and the corresponding readXXX() methods of DataInputStream to read them. 如果要写入更宽的值,则必须使用DataOutputStream,writeXXX()方法和相应的DataInputStream readXXX()方法来读取它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM