Tony Huang
Tony Huang

Reputation: 163

does close a socket will also close/flush the input/output stream

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?

Upvotes: 1

Views: 2574

Answers (2)

user207421
user207421

Reputation: 310860

  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.

Upvotes: 3

zjor
zjor

Reputation: 1043

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

Upvotes: 2

Related Questions