简体   繁体   English

JAVA:我无法从套接字读取文本,由 C++ 程序发送

[英]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++.情况:我有 JAVA 程序和 C++ 程序(只有 exe;我无法访问内部)。 They are sending and receiving text for eg "REQ", "00", "1,3", "15,4", "PAUSE" .他们正在发送和接收文本,例如"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 (...).首先RDY做了一个重复的命令: RDY number,number 20 RDY (...)。

Numbers: 0 - 15.数字: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"但有时我有 IOExeption:“输入长度 = 1”

Is there any solution, to read properly?有什么解决方案,可以正确阅读吗?

Your problem is, that in C/C++, a char is one byte, wheras a Java char is 2 bytes.您的问题是,在 C/C++ 中,一个char是一个字节,而 Java char是 2 个字节。 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 .尝试先读入一个byte数组(适当长度),然后创建一个相同长度的 char 数组,并通过将其转换为char来复制每个字节。 I'm sure you can do also some magic with stream encodings, but for your simple example, this should do!我相信你也可以用流编码做一些魔术,但对于你的简单例子,这应该可以!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM