ldam
ldam

Reputation: 4595

Java: Possible to have more than one type of stream?

Wondering if one can do something like this successfully:

Socket s = new Socket("", 1234);
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());
ObjectInputStream oin = new ObjectInputStream(s.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());

Or if there's perhaps a better way of doing it. I ask because I want to send raw data over the Buffered I/O streams and use the Object streams as a means of communicating details and establishing a protocol for connection for my program. Right now I'm trying to just use the Buffered streams and use byte arrays for my client/server protocol but I've hit a hiccup where the byte array I receive is not equal to what I expect it to be, so the == operator and .equals() method do not work for me.

Upvotes: 0

Views: 91

Answers (2)

DaoWen
DaoWen

Reputation: 33029

Go take a look at How can I read different groups of data on the same InputStream, using different types of InputStreams for each of them? and see if my answer over there helps. It involves tagging the data in an ObjectStream in order to know if it's text or an object.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533660

You can't use a mix of streams because they are both buffered so you will get corruption and confusion.

Just use the ObjectStreams for everything.

In general, you should only read from or write to one Stream, Reader or Writer for a stream.

Upvotes: 3

Related Questions