Reputation: 31
I am using TCP Socket in my java project. I am trying to receive data from some equipment. When ever the device is sending data from 0x80 to 0x9f, the data gets corrupted. For example if device is sending 0x86(134 in decimal) i am getting 0x2020(8224 in decimal). Please find below example code
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
int res = in.read() ;
Please let me know ,if anybody came across such issue. Any help is highly appreciated.
Aj
Upvotes: 1
Views: 329
Reputation: 86575
The InputStreamReader is reading bytes and converting them to chars (usually using UTF-8, unless you specify otherwise). And UTF-8 says that bytes with values over 127 are part of a multibyte char, so they could be combined with the next byte and give you a weird char code. Other encodings can do similarly wacky things, under the assumption that your bytes represent chars defined in the encoding's character set.
The fix: If you're reading bytes, read bytes (via an InputStream). If you're reading chars, read chars (via a Reader). Never confuse the two.
Upvotes: 2
Reputation: 1503290
You're using InputStreamReader
, which is in turn using the default character encoding for your platform because you haven't specified an encoding. Don't do that.
Are you genuinely trying to send and receive text? If so, explicitly use the same encoding on both sides (and make sure it's one which covers all the text you want to transmit - UTF-8 is usually a good bet). If not, don't use a Writer
/Reader
pair at all - they're meant for textual data.
Upvotes: 2