Java InputStream 0x0A issue
In Java I have the following
while(true) {
input = clientSocket.getInputStream();
byte[] bytes = new byte[4096];
int numRead=input.read(bytes, 0, bytes.length);
开发者_StackOverflow System.out.println(numRead);
}
When I send a stream of data locally, in hex 0A 48 08 05 12 20 44 36, I receive this in one go and the out put is:
8 (with the hex being 0A 48 08 05 12 20 44 36)
BUT when I run this across a wireless network I get the following output:
1 (with the hex being 0A)
7 (with the hex being 48 08 05 12 20 44 36)
Why is it doing this? I would expect it to return the value 8 (hex 0A 48 08 05 12 20 44 36)
Am I missing something here?
Thanks in advance
You cannot assume that a socket stream will deliver everything at once, even if it seems like it would fit into a packet. Servers along the route may choose to break up packets at line terminators (or anywhere else) for their own reasons, and you have no control over that. Accumulate the response in a ByteArrayOutputStream or similar buffer and process it once you get it all.
I had the same problem with the serial port. Apparently it's a bit-stuffing problem with the javax.comm API regaring Line Feed and Carriage Return codes (0x0a and 0x0d).
After googling around, I found the RXTX library.
Please, read this: http://wathsalav.blogspot.com/2006/01/suns-javaxcomm-driver-has-problems.html
Hope this helps!
Javadoc says this on InputStream.read(byte[] b,int off,int len):
Reads up to len bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len bytes, but a smaller number may be read. The number of bytes actually read is returned as an integer.
It did read 8 bytes, but in two steps, first 1 byte and then 7 bytes. If you're unlucky it could read 1 byte 8 times.
精彩评论