check socket alive

martinnitram at excite.com martinnitram at excite.com
Mon Feb 7 20:48:39 EST 2005


Dear all,
   following are some piece of my code (mainly create a socket
connection to server and loop to receive data):

   # function to create and return socket
   def connect():
    server_config = ('192.168.1.50', 3333);
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect()
    except socket.error:
        print "Failed to connect"
        return 0
    return sock

   # function to receive data
   def recv_for_sock(sock):
     sock.settimeout(25)
     while 1:
       if sock is None:
         return 1
       try:
         recv_data = sock.recv(65535)
         if recv_data:
           .... # do something
       except socket.timeout:
         print "Socket Timeout"
         time.sleep (10)
         pass
       except socket.error:
         print "Socket Error"
         time.sleep (10)
         pass

  # main function
  if __name__ == '__main__':
      sock = connect()
      if sock:
          errorno = recv_for_sock(sock)
          ... # other stuffs
      else:
          print "Cannot create connection"
          ...

  my question is, when the socket (create a main function) is
disconnected by server (netstat status show close_wait), in
"recv_for_sock" function, it can catch the timeout exception at first
time. After then, the program will looping/hang within the
"recv_for_sock" function (actually is the socket.recv function) and
causing CPU usage to 99%. So, how to detect the socket connection is
closed at this case? I tried to use exception/check socket is None but
no help.
    Thank for helping.




More information about the Python-list mailing list