2
OutputStreamWriter out = new OutputStreamWriter(sock.getOutputStream());

out.write(data);
out.flush();

sock - Socket; data - buffer of chars;

So, if I wouldn't close the "out", or "sock" then there is no data will be sent to server.

OutputStreamWriter out = new OutputStreamWriter(sock.getOutputStream());

out.write(data);
out.close();

Is fine. But why?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Alanir Alonedaw
  • 132
  • 1
  • 8
  • That shouldn't happen. Closing the output stream will close the socket, which is sometimes definitely not what you want. Are you sure no data is being sent to the server? Is the socket wrapping a channel? – Ted Hopp Sep 04 '11 at 03:35
  • Yes, I'm sure. Server-side demon is written by me too. So I have a lot of debug information on it's side. Socket is wrapping? What's this about? – Alanir Alonedaw Sep 04 '11 at 11:49
  • A Socket wraps a channel if it was created from a [SocketChannel](http://developer.android.com/reference/java/nio/channels/SocketChannel.html). Since you're asking what this means, I'm guessing your socket is not wrapping a channel. – Ted Hopp Sep 04 '11 at 13:25
  • I was able to found the problem: my server socket was in receiving state with MSG_WAITALL flag. – Alanir Alonedaw Sep 04 '11 at 14:02
  • Good to know. So that others might benefit, could you post your solution as an answer and mark it as solved? – Ted Hopp Sep 04 '11 at 20:08

1 Answers1

0

flush() only flushes Java's/Android's application level buffer to the TCP stack. Once there, it can be further delayed by the TCP implementation of the OS that tries to make efficient use of transmitted packets and waits for more data. (Search for "Nagle's algorithm" if you need more detail.)

There is no way to flush a TCP buffer per write to a socket, but the socket can be configured to immediately send all data in the buffer when possible, by setting TCP_NODELAY

See Java ObjectOutputStream on Socket not flush()ing for more information on the topic.

Community
  • 1
  • 1
lxgr
  • 3,719
  • 7
  • 31
  • 46