I have a TCP server for which I need to write a client in Python.
The server is an arduino using the arduino_uip library; the server code is (almost) the same as the TCP server example of that library. It works fine using nc as a client.
But when I use python sockets (as in this answer) to communicate with the server, the server hangs on socket shutdown or close.
That may be an issue with the server; however since nc is working fine as a client, my question is :
What does this answer do differently from nc that may explain server hanging on connection shutdown/close)?
Summing up what works & what not :
Here is the client 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()
Edit :
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...
Had a look at the netcat source ( svn checkout svn://svn.code.sf.net/p/netcat/code/trunk netcat-code ) and it only calls shutdown() just before it closes, not just after setting up the socket
That's the difference as far as I can see
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With