0

The problem is solved, see below...

I am currently developing a server-client application.

The server is programmed in C/C++ using openssl and the client is programmed in android-java using the SSLSocket class.
To write to the SSL-socket (client) I am using the BufferefWriter. I guess that is the main problem, but my research for my problem or for alternatives was not of success...

This is how I write data to the socket:

BufferedWriter out = new BufferedWriter(new PrintWriter(socket.getOutputStream(), true));
// This was a typo char[] data = new byte[] {0,0,0,255};
char[] data = new char[] {0,0,0,255};
out.write(data);

Now the server recieves 0,0,195,191
And that really confuses me!

But I guess it is due to the way the BufferedWriter works.

So what can I do in order to send binary data to the SSL socket?
What alternatives are there to the BufferedWriter?

Thanks for your time!

SOLVED

Ok thanks to McDowell and robermann I found the following sollution:

BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
byte[] data = new byte[] {0,0,0,255};
out.write(data);

I didn't know about the way java works with chars and thus was kind of confused.
For further information about the way chars are used in java take a look at McDowell's answer below.

Thanks to all you guys! :D

Ch33f
  • 609
  • 8
  • 17
  • 1
    Why are you confused? Anyway, you could write to a ByteArrayOutputStream – robermann Mar 02 '14 at 15:01
  • 1
    This won't compile: `char[] data = new byte[]...` - correct your code. Remember that a _char_ is 16bits wide and the _PrintWriter_ is performing a transcoding operation from UTF-16 to the platform encoding. A Java _char_ is more like a _wchar_t_; the Java _byte_ is an 8bit type with the same width as a C _char_. – McDowell Mar 02 '14 at 15:03
  • @Ch33f Maybe were you expecting to see encrypted data on the server? – robermann Mar 02 '14 at 15:03
  • @McDowell The char = new byte thing was a typo but I didn't know that char is 16-bit wide in java, well that explains a lot! Thanks! I'll try the ByteArrayOutputStram – Ch33f Mar 02 '14 at 15:11
  • 'BufferedWriter and binary data' is already a major programming error. If you have binary data, or you *don't* know that you definitely have character data, you must use streams, not readers and writers. – user207421 Mar 03 '14 at 22:46

1 Answers1

2
char[] data = new char[] {0,0,0,255};

char values are implicitly UTF-16BE. The default encoding on Android is UTF-8. For the given constructor the PrintWriter will perform a transcoding operation from UTF-16 to UTF-8.

The above values should become the 5-byte sequence 00 00 00 c3 bf which (bar a leading byte) you are seeing on the server.

Types like DataOutputStream or something more formal (like Google Protocol Buffers) may be more suitable for low-level binary protocols.

McDowell
  • 107,573
  • 31
  • 204
  • 267