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();
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202

2 Answers2

3

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

What is it you want to do?

Fredrik
  • 5,759
  • 2
  • 26
  • 32
  • Here is what I have done so far http://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? – Chris Seymour Dec 01 '11 at 16:55
  • @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: -) – Fredrik Dec 01 '11 at 17:15
  • 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`. – Chris Seymour Dec 01 '11 at 17:36
  • Reading further on this topic I have discovered that `obj` has to implement serializable `public class obj implements Serializable` – Chris Seymour Dec 02 '11 at 10:34
  • @sudo_o yes, that's a prerequisite for being able to use serialization and write object on a stream. – Fredrik Dec 02 '11 at 10:57
  • Thanks for your help, my first networking application is coming along nicely! – Chris Seymour Dec 02 '11 at 11:02
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.

Thomas Pornin
  • 72,986
  • 14
  • 147
  • 189