title: Forcing a TCP socket to flush in Java
body: <p>I'm developing a protocol that requires a handshake that consists of several pieces of information going back and forth in each direction, with several pieces dependent on the previous pieces (think like SSL/TLS handshake). I'm trying to implement it in Java.</p>
  
  <p>A lot of my packets are only 20-30 bytes, whereas my computer seems to think it needs to buffer hundreds of bytes before it sends anything; even if I wait 5-10 seconds (with Thread.sleep), it still won't actually send it until I close the socket.</p>
  
  <p>How can I get Java/my computer to send what's in its buffer?</p>
  
  <p>On other forums (and SO), a lot of people have been using arguments like "that's not how TCP works", "you shouldn't actually need that." If I need to send 10 packets each way, each one depends on the last, each one waits for 300ms in the TCP stack, I'm looking at 6s for my handshake, which is completely unusable. (Mind you, I can't get it to send at all, no matter how much I call flush on the socket; I can't get it sent at all until I close the socket).</p>
  
  <p>I have considered just sending a packet plus enough useless padding to force the TCP implementation to force it, that seems like a bad solution.</p>
  
  <p>(Simplified, extracted) Code:</p>
  
  <pre><code>Socket sock = new Socket("localhost", 1234);
  OutputStream output = sock.getOutputStream();
  output.write(new byte[] {(byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef});
  output.flush();
  Thread.sleep(5000);
  </code></pre>
  
  <p>[I've tried with PrintWriter, OutputStreamWriter; they don't help.]</p>