简体   繁体   English

无法从Java套接字服务器接收数据到C套接字客户端

[英]Trouble receiving data to C socket client from Java socket server

My Socket client is written in C and sends the values in the format below: 我的Socket客户端使用C语言编写,并按照以下格式发送值:

x00\x2C\x02\x00\xE0\x00

Now I would like to read the hex values from the TCP/IP socket server which is written in Java. 现在,我想从用Java编写的TCP / IP套接字服务器中读取十六进制值。

What should be a approach to read the stream values in Java Socket? 在Java Socket中读取流值的方法应该是什么?

I'm trying to read in the following way, but it does not work: 我正在尝试通过以下方式阅读,但是它不起作用:

InputStream ins = sock.getInputStream();
int byteRead;

while((byteRead = ins.read()) != -1) {
  System.out.println(Integer.toHexString(byteRead & 0xFF));
}

If you dont know the length of the message you will need to read each byte reperesentation into a String buffer and use Byte#parseByte(buffer, 16) to make a signed byte [-127, 127] out of it. 如果您不知道消息的长度,则需要将每个字节的表示形式读入字符串缓冲区,并使用Byte#parseByte(buffer,16)来从中生成一个有符号的字节[ -127,127 ]

If you know the length of the whole String that the client is sending you could read it all and then String#split(regex) it using a delimiter whicht seems to be in your case \\x . 如果您知道客户端发送的整个String的长度,则可以全部读取,然后使用定界符来String#split(regex)将其读入\\x and again make use of Byte#parseByte(buffer, 16) to convert. 并再次使用Byte#parseByte(buffer, 16)进行转换。

If you need unsigned values [0, 255] then you have to go with Integer.html#parseInt(buffer, 16) . 如果您需要无符号[0,255],则必须使用Integer.html#parseInt(buffer,16)

First stating the obvious, "\\x41" is one byte with hex 41 aka ASCII 'A'. 首先说明显而易见的是,“ \\ x41”是一个十六进制41(即ASCII'A')的字节。 C strings also have a terminating \\x00 following it. C字符串后面还有一个终止符\\x00 So you are writing 所以你在写

\x00\x2C\x02\x00\xE0\x00

as char array with size 6. Writing it as string would write an empty string, as the first byte is \\x00 . 作为大小为6的char数组。将其写入字符串将写入一个空字符串,因为第一个字节为\\x00

On the java side there is no problem with \\x00 , that is just a regular byte/char. 在Java方面, \\x00没问题,这只是一个常规字节/字符。

The java code is okay. Java代码还可以。 A variation might be: 一个变化可能是:

try (InputStream ins = new BufferedInputStream(sock.getInputStream())) {
    int byteRead;
    while ((byteRead = ins.read()) != -1) {
        System.out.printf("%02X%n", byteRead & 0xFF);
    }
} // Closes

Here capital X causes capitalized hex, and %na line break. 此处的大写X导致大写的十六进制和%na换行符。 String.format would be the alternative. String.format

My first guess would be that the C writing is erroneously done with puts , using strlen or so. 我的第一个猜测是,在C写入错误地做puts ,使用strlen左右。

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

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