check socket alive

Steve Horsley shoot at the.moon
Wed Feb 9 18:18:54 EST 2005


martinnitram at excite.com wrote:
> Dear all,
>    following are some piece of my code (mainly create a socket
> connection to server and loop to receive data):
<snip> 
>    # 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
> 
<snip> 
>   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.
> 

There is no point in continuing round the loop once you have caught an
exception. I suggest two possibilities:

1) put a return statement in the catch blocks, and return an ppropriate
value that indicates an error.

Or better:

2) Don't catch the exception at this level (because this method doesn't
know how to deal with the situation properly). Instead, let the exception
bubble up the call stack, and catch and deal with the exception wherever
you ARE able to sensiby able to decide what on earth to do if the receive
goes wrong.

Steve



More information about the Python-list mailing list