Reputation: 947
I'm trying to write 0x87 in a Java socket I've created.
tcpSocket = new Socket(server, port);
tcpWriteToServer = new PrintWriter(tcpSocket.getOutputStream(), true);
byte [] header = {0x8, 0x7};
tcpWriteToServer.print(header);
On the server side I get:
Incoming Bytes: 0x5b 0x42 0x40 0x34 0x32 0x65 0x62 0x35 0x62 0x38 0x38
I tried to break down the problem and just send one byte:
tcpWriteToServer.print(header[0]);
For this I end up getting:
Incoming Bytes: 0x38
I'm not sure how that "3" in "0x38" gets read. I read "0x37" when I try to send "0x7".
The server side is written in python and I have no issues sending the bytes and reading correctly in python.
Any idea what I might be missing?
Upvotes: 0
Views: 1519
Reputation: 533820
Any idea what I might be missing?
You have to decide whether you want to write text or binary. Combining them is likely to be a good way to confuse yourself.
I suggest you use binary in this case.
tcpSocket = new Socket(server, port);
out = tcpSocket.getOutputStream();
out.write(0x8);
out.write(0x7);
You can also buffer the output like this.
out = new BufferedOutputStream(tcpSocket.getOutputStream());
out.write(0x8);
out.write(0x7);
out.flush();
If you have an array of bytes you can write them in one go.
byte[] header = { .... };
out.write(header);
I'm not sure how that "3" in "0x38" gets read. I read "0x37" when I try to send "0x7".
There is no print(byte)
but there is a print(int)
so when you do
print(8);
it is the same as
print(Integer.toString(8));
or
print("8");
or
print('8')
and '8' = 0x38 in ASCII
Upvotes: 3
Reputation: 124275
Incoming Bytes: 0x5b 0x42 0x40 0x34 0x32 0x65 0x62 0x35 0x62 0x38 0x38
If you print out character representation of each of this bytes
byte[] bytes = {0x5b, 0x42, 0x40, 0x34, 0x32, 0x65, 0x62, 0x35, 0x62, 0x38, 0x38};
for (byte b : bytes){
System.out.print((char)b);
}
you will see that your code sends [B@42eb5b88
.
It happens because since PrintWriter has no print(byte[])
method it uses print(Object obj)
which just sends String representation of object obj
. Such string is created with String.valueOf(obj)
which internally is using obj.toString()
method, which for arrays returns typeName
([b
- one dimensional [
array of bytes b
), @
and hexHashCode
.
In other words you didn't send content of header
array, but result of its toString()
method.
If you want to send bytes it is easier to use Stream
(Writers ware meant to handle text, not bytes) and their write(byte[])
method. If you want to be also able to send text instead of bytes you can use PrintStream
PrintStream tcpWriteToServer = new PrintStream(tcpSocket.getOutputStream(), true);
tcpWriteToServer.write(header);
Upvotes: 1