I h开发者_JAVA百科ave this line of code in my server/client pair:
BufferedOutputStream out = new BufferedOutputStream (clientSocket.getOutputStream());
It works fine, the code works well, then if I modify it to:
BufferedOutputStream out = new BufferedOutputStream (new BufferedOutputStream(clientSocket.getOutputStream()));
The execution of the application will halt where outputs are sent. I really only made that modification and am very new to streams in this manner, especially sockets.
Is there any obvious error?
Yes, this would be consistent with the behaviour of BufferedOutputStream
, which as its name suggests will buffer output before sending it.
When you write objects to the ObjectOutputStream
, the bytes will be passed along to the BufferedOutputStream
, which will only send them on to the socket when its buffer fills up. So your objects will be "hanging around" in the buffer, waiting to be flushed. So your outputs are not really "sent", since they haven't made it as far as the socket.
If you want to keep using BufferedOutputStream
, then you may need to periodically flush()
it, in order to keep things moving along. The flush()
method on the ObjectOutputStream
will in turn call flush()
on the BufferedOutputStream
, which will empty the buffer and send the objects down the pipe.
I have to ask, though, why you need to use BufferedOuputStream
at all. Do you have a performance problem that needs buffering to solve? If not, then just leave it out, it adds complexity that you may not need.
精彩评论