On the moment i'm busy making a litte program that sends a hexadecimal stream to a client.
Now what i do is split the stream and convert every 2 digits to a char. The output of that i convert back to a string so that i can send the data. For debugging i'm using wireshark to see if the sended data is correct.
But it isn't correct. And i know why. Because for example i use b7 (dec 183) and char only supports until 127. But now the problem is, i don't know how to solve the problem ..
Can you help to fix my code ? Thanks !
ServerSocket welcomeSocket2 = new ServerSocket(9999);
Socket socket2 = welcomeSocket2.accept();
OutputStream os3 = socket2.getOutputStream();
OutputStreamWriter osw3 = new OutputStreamWriter(os3);
BufferedWriter bw3 = new BufferedWriter(osw3);
String hex4 = "00383700177a01020a6cb7000000000000018fffffff7f030201000a080000000000000000184802000007080444544235508001000002080104";
StringBuilder output4 = new StringBuilder();
for (int i =0; i< hex4.length(); i +=2){
String str4 = hex4.substring(i, i+2);
int outputdecimal = Integer.parseInt(str4,16);
char hexchar = (char)outputdecimal;
System.out.println(str4);
output4.append(hexchar);
}
bw3.write(output4.toString());
This is what i get in wireshark :
0000 00 38 37 00 17 7a 01 02 0a 6c c2 b7 00 00 00 00
0010 00 00 01 c2 8f c3 bf c3 bf c3 bf 7f 03 02 01 00
0020 0a 08 00 00 00 00 00 00 00 00 18 48 02 00 00 07
0030 08 04 44 54 42 35 50 c2 80 01
But the correct data i must get in wireshark is this :
0000 00 38 37 00 17 7a 01 02 0a 6c b7 00 00 00 00 00
0010 00 01 8f ff ff ff 7f 03 02 01 00 0a 08 00 00 00
0020 00 00 00 00 00 18 48 02 00 00 07 08 04 44 54 42
0030 35 50 80 01 00 00 02 08 01 04
Alternatively, if you want to write bytes to a socket, you can do that directly, rather than with extra agreements about character encodings and conversions to and from text.
There are no unsigned bytes in Java. Nonetheless, byte[]
is often used for transferring raw data.
Sample data:
byte[] data = { 0x00, 0x01, 0x7f, (byte)0x80, (byte)0xfe, (byte)0xff };
(There are no byte
literals in Java. Literal values are coerced from int
to byte
, using the cast syntax to override the compiler's range checking where needed.)
FilterOutputStream
has a convenient method to write a byte array to an output stream.
ServerSocket welcomeSocket2 = new ServerSocket(9999);
Socket socket2 = welcomeSocket2.accept();
OutputStream os3 = socket2.getOutputStream();
FilterOutputStream out = new FilterOutputStream(os3);
out.write(data);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.