1

I'm new to socket programming, and I've been following several tutorials like this one http://www.myandroidsolutions.com/2012/07/20/android-tcp-connection-tutorial/ and was able to build a client-server architecture over TCP using socket.

The thing is, the tutorials are basic so they teaches you how to send using PrintWriter and BufferedReader which seems to write and read String. I have to encrypt my data and send it as byte[], so the question will be:

  1. For this mean, can I still use PrintWriter and BufferedReader? if not then
  2. What classes should I use for this means and how?, I have seen DataOutputStream and DataInputStream and several others, but have not found their difference or why use one or another.

PS: The encryption part is already done, so don't worry about it as it is not the question :)

1 Answer 1

7

You should use an OutputStream to write and an InputStream to read. Those are for binary data - anything with a suffix of Writer or Reader is for text data.

You may find DataOutputStream and DataInputStream useful - they basically add some services wrapped around a vanilla OutputStream. But if all you need to do is write a byte[] to a stream, then plain OutputStream is fine.

Sign up to request clarification or add additional context in comments.

4 Comments

Side-question of mine. Do sockets buffer the data automatically, or will a write call, send an actual TCP packet? I used to wrap it in a BufferedOutputStream, but I'm not sure wether this is needed.
@MartijnCourteaux: I believe sockets will buffer automatically (e.g. at the OS or network adapter level), but it could be that using a BufferedOutputStream will buffer more.
ok, now that you mention binary data, maybe I have some concept wrongs. The reason I'm writing byte[] is cause the AES encryption procedure returns a byte[], but I'm actually sending a JSON string. Should I encrypt it differently so I can write text (since I'm not actually sending binary data as files or bitmaps) ? Also, as a side question, is sending JSON over TCP is considered correct, or does data format has an standard?
@ChristopherFrancisco: No, you're sending binary data - that's fine :) When I say "text data" I mean "strings that are encoded using an encoding like UTF-8 or ISO-8859-1". The result of encryption definitely counts as binary data. Of course if your encryption lends itself to streaming, you could create an OutputStreamWriter which layered on top of your EncryptingOutputStream which itself would write to the underlying OutputStream...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.