2

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.

cstjh
  • 153
  • 1
  • 2
  • 8
  • Can you give us minimum working example? You say you send data to server and server responds, but then all you have on server side is sending and not receiving. – Ilija Feb 12 '18 at 22:19
  • 2
    Dup of https://stackoverflow.com/a/48613168/1076479 (with client and server swapped) – Gil Hamilton Feb 12 '18 at 22:49
  • @GilHamilton I don't 'select' will work in my case. 'select' will tell me if the socket is readable and after reading EOF from the socket, the server will know the socket status. Right? But in my program, if the client doesn't crash, the server will send the message correctly. If I add a 'select' to read something from the socket, the 'recv' might block the socket and I cannot send messages to the available client. What should I do in this case? – cstjh Feb 13 '18 at 04:20
  • 2
    You can specify a timeout to the `select`. If you specify a timeout of zero, you can essentially poll for the status -- i.e. check whether it has become readable since the last time you used it. If it is not readable, don't call `recv` (hence don't block); simply infer that your peer has not closed the socket. There are other ways to structure this too (read in a separate thread, for example). – Gil Hamilton Feb 13 '18 at 18:42

0 Answers0