Best practice for reading until a marker with sockets (Java)?
I'm creating a mobile app to run on a phone and trying to read data from it in the most efficient way. The application will send data to my server app (in the form of bytes, not necessarily characters).
I won't know the length of the data; the end will be marked with a 3 byte marker (i.e. 0x11,0x22,0x33), and then a new set of data will be sent. It is likely that a large amount of data will be sent in each "set" of data. I'm wondering, then, what the most efficient way to read this data is. Should I use InputStreamReader
? BufferedReader
? Obviously, I will need to inspect each character t开发者_如何学Goo see if it is part of the marker, and if so, send all the data before the marker to another method for processing.
From what I can tell, BufferedReader.readLine()
would be what I want if my end marker was a \n
(obviously, this is not the case). Do I need to write my own method to read a BufferedReader
byte-by-byte and look for my marker? (I also do not know if this would be the most efficient way?)
Assuming that your data is byte data rather than character data, you should wrap your socket input stream in a BufferedInputStream
, and use that to read the data one byte at a time, saving the bytes in a byte buffer of some kind. (One option is to use a ByteArrayOutputStream
to buffer the data bytes that you've read from the BufferedInputStream
.)
BufferedReader
and readLine()
are NOT the way to go:
- Assuming that the data is not character data, if you attempt to decode it according to some character set, you are liable to mangle it.
- The
readLine
method only understands lines separated by'\n'
and/or'\r'
characters. There's no way to get it to understand other "line" separators.
Finally, note that the BufferedInputStream
is very important for performance reasons. If you don't use one, and read from the socket InputStream one byte at a time, you are likely to incur a significant performance hit due to the number of syscalls that your Java app performs.
A Reader is for reading text, so you probably want an InputStream instead. Streams generally are more efficient when you buffer them, so use BufferedInputStream. And I don't know of any built-in function to detect markers in stream data, so you'll have to do that yourself.
精彩评论