1

I have a program like that,

Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();

...some read and write here...

socket.close;

The code works fine. But I am not sure whether the in/out was close if I close the socket or not. Also I didn't call out.flush(), how the data going to be sent out?

Tony Huang
  • 163
  • 3
  • 13
  • 1
    See http://stackoverflow.com/questions/3428127/what-is-the-difference-between-closing-input-outputstream-and-closing-socket-dir – zjor Oct 10 '13 at 22:05
  • looks like closing the socket will close the input/output stream associate with this socket. But will the outputStream get flush? – Tony Huang Oct 10 '13 at 22:15

2 Answers2

3
  1. Closing the socket doesn't flush the output stream but closes both streams and the socket.
  2. Closing the input stream doesn't flush the output stream but closes both streams and the socket.
  3. Closing the output stream flushes it and closes both streams and the socket.

You should close the outermost OutputStream you have wrapped around the one you got from the socket. For example:

BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);

Close 'dos'. That flushes it, flushes 'bos', and closes everything.

Flush on close is documented in the Javadoc for FilterOutputStream.

user207421
  • 305,947
  • 44
  • 307
  • 483
2

Another answer: In Java, when I call OutputStream.close() do I always need to call OutputStream.flush() before?

says that yes! It will be flushed if you close it manually

Community
  • 1
  • 1
zjor
  • 994
  • 2
  • 12
  • 22