I am working on socket programming in python and I want to detect client socket disconnection on server side.
Client:
socket.connect(host, port)
try:
""" send something to server and get response from the server"""
except KeyboardInterrupt:
socket.shutdown(socket.SHUT_RDWR)
socket.close()
Server:
conn, address = socket.accept()
try:
conn.send(message)
except:
print "-1"
But when I first run this code, I close the client by keyboard interrupt and the server won't print -1 in the screen. When I try it again, the server will catch the exception and print -1.
I wonder if there is something wrong with my code. Why the server won't detect the disconnection at the first time?
Thanks.