简体   繁体   English

将十六进制字符串作为字节写入套接字Java

[英]write hex string as bytes to socket java

I have a string of hex values that I am trying to write to a socket as bytes. 我有一个十六进制值字符串,我试图将其作为字节写入套接字。

String confDeliv = "\\x7E\\x01\\x00\\x20\\x37\\x02\\x03\\xF2\\xD5";

I have tried doing this to try and solve my problem 我已经尝试过这样做以解决我的问题

byte [] Delivery_Conf = {(byte)0x7E, (byte)0x01, (byte)0x00, (byte)0x20,
                             (byte)0x37, (byte)0x02, (byte)0x03, (byte)0xF2, (byte)0xD5};

But I have yet to succeed to write it to the socket. 但是我尚未成功将其写入套接字。 I don't get any errors but when I send it to the device it doesn't do what I need it to do I have tried two different ways of doing this. 我没有收到任何错误,但是当我将其发送到设备时,它没有执行我需要做的事情,我尝试了两种不同的方法来执行此操作。

Try 1: 尝试1:

DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());                                           //69.171.154.64

    for (int i = 0; i < Delivery_Conf.length-1; i++) {
        dOut.writeByte(Delivery_Conf[i]);
    }
dOut.flush();

This method I used when I but the values into a byte array. 当我将值放入字节数组时,我使用了此方法。

Try 2: 尝试2:

DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());                                           

            dOut.writeBytes(confDeliv);
            dOut.flush();

This is the method I used when I tried sending it as the string but still no luck. 这是我尝试将其作为字符串发送但没有运气时使用的方法。 I am able to make the device work when I use python using its byte string. 当我使用带字节字符串的python时,我能够使设备正常工作。

eg. 例如。

confDel = b"\x7E\x01\x00\x20\x37\x02\x03\xF2\xD5"

I think java changes something when I send it and I think that is why I can get it to work with java. 我认为Java在发送时会有所更改,这就是为什么我可以使其与Java一起使用的原因。 I have looked around for while but I do not seem to find anything that will help me with my problem. 我环顾了片刻,但似乎找不到任何能帮助我解决问题的东西。

You should use the following: 您应该使用以下内容:

byte [] Delivery_Conf = {(byte)0x7E, (byte)0x01, (byte)0x00, (byte)0x20,
                         (byte)0x37, (byte)0x02, (byte)0x03, (byte)0xF2, (byte)0xD5};
// ...
dos.write(Delivery_conf);

The version you had writing a byte at a time should work but it's inefficient, and it's possible that the device has timing constraints. 您一次写入一个字节的版本应该可以工作,但是效率低下,并且该设备可能具有时序限制。

The version using the String isn't correct. 使用String的版本不正确。 Adding another backslash to make \\x compile is not a correct solution: you should change \\x to \\u00\u003c/code> throughout. 添加另一个反斜杠以使\\x编译不是正确的解决方案:您应始终将\\x更改为\\u00\u003c/code> 。 Throughout the string, that is, of course. 当然,在整个字符串中。

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

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