Using BufferedOutputStream makes the application stop

I have this line of code in my server / client pair:

BufferedOutputStream out = new BufferedOutputStream (clientSocket.getOutputStream()); 

It works fine, the code works fine, then if I change it:

 BufferedOutputStream out = new BufferedOutputStream (new BufferedOutputStream(clientSocket.getOutputStream())); 

Application execution will be stopped when the output is sent. I really only made this modification and am very new to threads this way, especially sockets.

Is there an obvious mistake?

+4
source share
1 answer

Yes, this will be consistent with the behavior of the BufferedOutputStream , which, as its name implies, will output a buffer before sending.

When you write objects to an ObjectOutputStream , bytes will be transmitted along with the BufferedOutputStream , which will only send them to the socket when its buffer is full. Thus, your objects will "hang" in the buffer, waiting for you to turn red. This way your outputs are not actually sent because they did not reach the socket.

If you want to continue to use BufferedOutputStream , you may need to flush() it periodically so that everything is in order. The flush() method on ObjectOutputStream in turn call flush() on a BufferedOutputStream , which will free the buffer and send objects down the pipe.

I have to ask why you need to use BufferedOuputStream at all. Do you have a performance issue requiring buffering? If not, then just leave it, this will add complexity that you might not need.

+6
source

All Articles