title: Sending data through broken pipe
body: <p>When I connect a socket to a server socket, and the server socket at a given time shuts down, I get a <code>BrokenPipeError</code> on the client side. But not the next time I try to send something, but the time after that.</p>
  
  <p>Here a SSCCE:</p>
  
  <p>Server:</p>
  
  <pre><code>#! /usr/bin/python3
  
  import socket
  
  s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
  s.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind ( ('', 10100) )
  s.listen (1)
  print ('Waiting on client')
  client, _ = s.accept ()
  print ('Accepted')
  data = b''
  done = False
  while not done:
      data += client.recv (4096)
      msgs = data.split (b'\r')
      for msg in msgs [:-1]:
          print ('received {}'.format (msg) )
          done = msg == b'exit'
      data = msgs [-1]
  s.close ()
  print ('Server down')
  </code></pre>
  
  <p>Client: </p>
  
  <pre><code>#! /usr/bin/python3
  
  import socket
  
  s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
  print ('Connecting')
  s.connect ( ('localhost', 10100) )
  print ('Connected')
  for msg in [b'ping', b'pang', b'exit', b'ping', b'pang']:
      print ('Sending {}'.format (msg) )
      sent = s.send (msg + b'\r')
      print ('Sent {}. {} bytes transmitted'.format (msg, sent) )
      input ('&gt;&gt; ')
  </code></pre>
  
  <p>I start up the server, then the client and hit enter to step through the messages.</p>
  
  <p>The server output is:</p>
  
  <pre><code>Waiting on client
  Accepted
  received b'ping'
  received b'pang'
  received b'exit'
  Server down
  </code></pre>
  
  <p>The client output is:</p>
  
  <pre><code>Connecting
  Connected
  Sending b'ping'
  Sent b'ping'. 5 bytes transmitted
  &gt;&gt; 
  Sending b'pang'
  Sent b'pang'. 5 bytes transmitted
  &gt;&gt; 
  Sending b'exit'
  Sent b'exit'. 5 bytes transmitted
  &gt;&gt; 
  Sending b'ping'
  Sent b'ping'. 5 bytes transmitted
  &gt;&gt; 
  Sending b'pang'
  Traceback (most recent call last):
    File "./client.py", line 10, in &lt;module&gt;
      sent = s.send (msg + b'\r')
  BrokenPipeError: [Errno 32] Broken pipe
  </code></pre>
  
  <p>Why do I get the <code>BrokenPipeError</code> after the last <code>pang</code> and not after the <code>ping</code>?</p>
  
  <p>Why does <code>send</code> return 5 when sending the <code>ping</code> after the <code>exit</code>?</p>
  
  <p>Why is the pipe not broken immediately after the server is down?</p>
  
  <hr>
  
  <p>EDIT: After having sent <code>exit</code>, I don't hit enter on the client console unless the server console has already printed <code>Server down</code>.</p>