Good day,
I am having some trouble. I am trying to send a character array over the network to a server.
here is my code:
char[] arr= {3,4};
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.print(arr);
out.flush();
}
}
When I run that, lanshark detects that it recieved a packet with 2 bytes of data. ok good all is well.
Now when i run this:
char[] arr= {3,160}; // notice 160 *****
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.print(arr);
out.flush();
}
}
lanshark says that the packet has 3 bytes of data? the exact data is :
03 c2 a0
Now why is it adding the c2 in there? i understand that it has some thing to do with the fact that my char is bigger than 127. But i need to send this value of 160 .
Please can you help me. Do i need to use another type of data, or send it in a different way? I know you can do this in C. How can i do it in java?
here is the code for my out object:
PrintWriter out;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Thanks
In fact, the program is doing exactly what you told it to do. It is sending two characters; i.e. the unicode codepoints
3(\u0003) and160(\u00a0). These characters are being encoded using your platform’s default character encoding … which appears to be UTF-8. The bytesc2 a0are the UTF-8 encoding for the\u00a0character.But what you are actually trying to do is send 2 bytes.
In Java
charis a 16 bit type, not an 8 bit type. If you want to send 8 bit values you need to use thebytetype.The other mistake you are making is that you are trying to send (essentially) binary data using a
Writer. TheWriterinterface is for (16-bit) character oriented data. You should be using theOutputStreamAPI …Anyhow … here’s a code snippet to illustrate how you should send an array of bytes;
You are making it worse!
Lets take this apart:
new String(arr)gives you a 2 character String..getBytes(...)will turn that into a 3 byte array containing the bytes03 c2 a0.out.print(...)will attempt to call aprintmethod on thePrintWriterAPI.But which one? Well you supplied an argument whose declared type is
byte[]. And that will result in you callingprint(Object).But wait a minute … what does
PrintWriter.print(Object)do? Well the first thing is that it does is to calltoString()on the argument.And what does that do? Well since the object is a
byte[], this calls the defaulttoString()method provided byjava.lang.Object. And that gives you a String that looks likeB[@xxxxxxxxwhere[Bis the “class name” for a byte array, and the sequence ofxs is a hexadecimal representation of the array object’s identity hashcode!And then you output that that String.
And behold your 2 bytes (actually characters) have turned into 11 bytes.