python sockets: how to detect that client has closed/disconnected from the server side

I have a small server side program which accepts the connections from the clients and writes into the socket. I want to detect from the server side as soon as the client gets disconnected. I see the client has sent a TCP Fin when it disconnected and the server is detecting it only when it has some data to send towards the client and I see Broken pipe exception. Instead I want the server to be able to detect that the client has sent a Finish and immediately close the session. Can someone please help me by giving some inputs.

>>> Error sending data: [Errno 32] Broken pipe
[DEBUG] (Keepalive-Thread) Exiting

Server program to accept connections:

def enable_pce(ip):
  #Step 1: Create a TCP/IP socket to listen on. This listens for IPv4 AFI
  srv = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

  #Step 2: Prevent from "address in use" upon server restart
  srv.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

  #Step 3: Bind the socket to you server ip address

  srv_address = (ip,55555)
  print 'starting server on %s port %s' % srv_address
  srv.bind(srv_address)

  #Step 4: Listen for connections
  srv.listen(1)

  #Step 5: Wait for incoming connections

  connection, peer_address = peer.accept()
  print 'connection from', connection.getpeername()
  return connection

Upvotes: 2

Views: 10027

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123320

the server is detecting it only when it has some data to send towards the client and I see Broken pipe exception.

Close of connection by the peer can be detected either by getting an error when writing to the socket (broken pipe) or by reading from the socket and getting nothing (no error, no data) back.

In most scenarios it only matters to detect disconnection if one wants to communicate with the peer (that is read or write). If you want to do this without actually reading or writing data you might check readability of the socket with select.select and if the socket is readable peek into the read buffer with recv and MSG_PEEK.

Upvotes: 5

Related Questions