1

Can you have an PrintWriter and ObjectOutputStream on the same sockets output stream?

out_stream = new PrintWriter(socket.getOutputStream(), true);
obj_stream = new ObjectOutputStream(socket.getOutputStream();

2 Answers 2

3

I would say yes but I don't think I would do it.

What is it you want to do?

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

6 Comments

Here is what I have done so far stackoverflow.com/questions/8272726/distributed-system, I am now trying to implement that the worker machines have to be sent the 'doSomething()' method from the manager. I thought I could achieve this by sending an object using the ObjectOutputStream class?
@sudo_o I still don't really see the need to mix them, it just adds complexity in the other end when you need to read some data as objects and some as text. But good luck: -)
There isn't a need, My framework passes strings the way I want it to and I don't want to break that. Now I'm trying to send an object but instead of changing all of the PrintWriters in my classes I am keeping it separate whilst I work on it. However when I try and send an object w_obj.writeObject(obj); it throws and IOExpection.
Reading further on this topic I have discovered that obj has to implement serializable public class obj implements Serializable
@sudo_o yes, that's a prerequisite for being able to use serialization and write object on a stream.
|
1

You can but you have to take care of buffering. A PrintWriter or an ObjectOutputStream accepts data, which it converts into bytes, to be sent on the underlying stream (here the socket) at some point. Buffering is about waiting a bit before writing out such bytes, so that the bytes can be sent in "big chunks" rather than individually.

Read the Javadoc about buffering, and use flush() on PrintWriter and ObjectOutputStream when you want to get sure that the bytes get written on the socket.

Comments

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.