Wiszen
Wiszen

Reputation: 77

JAVA: I can't read text from sockets, send by C++ program

Situation: I have program in JAVA and program (only exe; I can't have access inside) in C++. They are sending and receiving text for e.g. "REQ", "00", "1,3", "15,4", "PAUSE". Communication goes like this (sending):

J: REQ
C: 00
J: NEW
C: 10
J: RDY
C: 2,13
J: 20
C: RDY
J: 1,1
(...)

First RDY made a repeated commands: RDY number,number 20 RDY (...).

Numbers: 0 - 15.

Receiving:

 char[] bb = new char[10];
 int znaki = in.read(bb);
 bb[7] = '\n';
 String s = new String(bb, 0, 7);

Problem: I read numbers like:

Send: 2,13
Received: 2,
Send: 3,15
Received 3,1
Send: 13,2
Received: 13,

But sometimes I have IOExeption: "Input length = 1"

Is there any solution, to read properly?

Upvotes: 1

Views: 82

Answers (1)

Philipp Lengauer
Philipp Lengauer

Reputation: 1959

Your problem is, that in C/C++, a char is one byte, wheras a Java char is 2 bytes. Try reading into a byte array first (of the proper length) and then create a char array of the same length and copy every byte by casting it to a char. I'm sure you can do also some magic with stream encodings, but for your simple example, this should do!

Upvotes: 1

Related Questions