title: python equivalent of netcat
body: <p>I have a TCP server for which I need to write a client in Python.</p>
  
  <p>The server is an arduino using the <a href="https://github.com/ntruchsess/arduino_uip" rel="nofollow noreferrer">arduino_uip</a> library; the server code is (almost) the same as the <a href="https://github.com/ntruchsess/arduino_uip/blob/master/examples/TcpServer/TcpServer.ino" rel="nofollow noreferrer">TCP server example of that library</a>. It works fine using nc as a client.</p>
  
  <p>But when I use python sockets (as in <a href="https://stackoverflow.com/a/1909355/2775518">this answer</a>) to communicate with the server, the server hangs on socket shutdown or close.</p>
  
  <p>That may be an issue with the server; however since nc is working fine as a client, my question is :</p>
  
  <p><strong>What does <a href="https://stackoverflow.com/a/1909355/2775518">this answer</a> do differently from nc that may explain server hanging on connection shutdown/close)?</strong></p>
  
  <p>Summing up what works &amp; what not :</p>
  
  <ul>
  <li>python client &amp; nc -l as server: works</li>
  <li>nc as client &amp; arduino server : works</li>
  <li>python client &amp; arduino server: hangs server</li>
  </ul>
  
  <p>Here is the client code :</p>
  
  <pre><code>import socket
  
  def netcat(hostname, port, content):
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      s.connect((hostname, port))
      s.sendall(content)
      s.shutdown(socket.SHUT_WR)
      while 1:
          data = s.recv(1024)
          if data == "":
              break
          print "Received:", repr(data)
      print "Connection closed."
      s.close()
  </code></pre>
  
  <p>Edit :</p>
  
  <p>It appears (Vorsprung's answer made me think about it!)that it is in fact a timing problem. If I add sleep(0.5) before shutdown in the above code all works nicely (as in netcat where there is a manual delay before I hit Ctrl+C). I suppose I'll have to check that arduino library now... </p>