问题
I have to write a JAVA program which communicates with some other program in C++. Messages to send are simple String/Char[] like "REQ", "PAUSE", "02,14" with '\0' on the end, so: "REQ\0". I have this:
socket = new Socket();
socket.connect(new InetSocketAddress(komputer, port), czekaj);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
Sending:
public void sendTekst(String tekst){
try{
char []a = tekst.toCharArray();
for(int i = 0; i < a.length; i++)
out.writeChar(a[i]);
out.writeChar((byte)'\0');
out.flush();
} catch(IOException e) {
JOptionPane.showMessageDialog(ramka, "Blad wysylu: " + e.getMessage());
}
}
Reading:
String s = null;
char aa;
while((aa = in.readChar()) != '\0'){
if(s == null)
s = String.valueOf(aa);
else
s += String.valueOf(aa);
}
Problem: I send "REQ" to C++ program (work on localhost on valid port). It received only garbage. I tried to do it on the same program (Java communicate Java) and it worked. What do I need to do?
I cannot edit the C++ program.
EDIT: I've changed input and output streams, but there is still problem:
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
Sending:
public void sendTekst(String tekst){
tekst += '\0';
char []a = tekst.toCharArray();
out.print(a);
out.flush();
}
Reading:
String s = null;
char[] aa = new char[20];
in.read(aa, 0, 10);
s = charToString(aa);
My method charToString:
public static String charToString(char[] buff){
String str = String.valueOf(buff[0]);
for(int i = 0; buff[i] != '\0' || i < buff.length ; i++)
str += String.valueOf(buff[i]);
return str;
}
I've tested this only for JAVA. I received garbage.
来源:https://stackoverflow.com/questions/37005553/communication-between-c-and-java