1
OutputStream out = socket.getOutputStream();
out.write(someData);
socket.close();

Will socket.close() cause the peer socket not to receive someData?

zhh
  • 2,346
  • 1
  • 11
  • 22
  • Did you read javadocs before asking? – rkosegi Oct 15 '17 at 05:19
  • Use [Socket#shutdownOutput()](http://download.java.net/java/jdk9/docs/api/java/net/Socket.html#shutdownOutput--) before calling `close()` – AJNeufeld Oct 15 '17 at 05:21
  • Of course the connection is lost. If you want to transfer any data after closing the socket then new socket must be created. – Kishor Oct 15 '17 at 05:21
  • @AJNeufeld Unnecessary. Why do you think otherwise? – user207421 Oct 15 '17 at 10:11
  • @Kishor The question is about lost data, not a lost connection. – user207421 Oct 15 '17 at 10:12
  • @EJP Proper socket shutdown & close is a 4-step process where FIN gets sent and acknowledged by both sides. Doing so allows rapid reuse of the socket ports by the server and by proxy/NAT devices. Without the proper shutdown sequence, the socket resources must remain allocated for the “linger” time configured on the socket. This is necessary for the remote client to be able to NAK reception of the last packet, requesting retransmission. Abruptly closing the socket without the proper shutdown could result in lost data if the linger period is not long enough. – AJNeufeld Oct 15 '17 at 19:39
  • @AJNeufeld Closing the socket sends a FIN if it hasn't already been sent by shutdown. Shutdown before close is unnecessary. There are several mistakes in your comment, including conflating the linger time with the TIME_WAIT time: they are completely different things. I can recommend my book if you want further information. All that has nothing to do with the actual question. – user207421 Oct 16 '17 at 00:52

1 Answers1

2

Will socket.close() cause the peer socket not to receive someData?

Definitely not, in this case. It will enqueue a FIN, which can only be received by the peer as end of stream after receiving all pending data.

However as a general rule you should call out.close(), to ensure any data buffered in out gets flushed, in case out was a buffered stream, rather than socket.close(), which doesn't care about whatever buffered streams may have been wrapped around its output stream.

user207421
  • 305,947
  • 44
  • 307
  • 483