How to tell if a connection is dead in python

前端 未结 5 629
忘掉有多难
忘掉有多难 2020-11-29 23:41

I want my python application to be able to tell when the socket on the other side has been dropped. Is there a method for this?

5条回答
  •  囚心锁ツ
    2020-11-30 00:21

    From the link Jweede posted:

    exception socket.timeout:

    This exception is raised when a timeout occurs on a socket
    which has had timeouts enabled via a prior call to settimeout().
    The accompanying value is a string whose value is currently
    always “timed out”.
    

    Here are the demo server and client programs for the socket module from the python docs

    # Echo server program
    import socket
    
    HOST = ''                 # Symbolic name meaning all available interfaces
    PORT = 50007              # Arbitrary non-privileged port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    print 'Connected by', addr
    while 1:
        data = conn.recv(1024)
        if not data: break
        conn.send(data)
    conn.close()
    

    And the client:

    # Echo client program
    import socket
    
    HOST = 'daring.cwi.nl'    # The remote host
    PORT = 50007              # The same port as used by the server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.send('Hello, world')
    data = s.recv(1024)
    s.close()
    print 'Received', repr(data)
    

    On the docs example page I pulled these from, there are more complex examples that employ this idea, but here is the simple answer:

    Assuming you're writing the client program, just put all your code that uses the socket when it is at risk of being dropped, inside a try block...

    try:
        s.connect((HOST, PORT))
        s.send("Hello, World!")
        ...
    except socket.timeout:
        # whatever you need to do when the connection is dropped
    

提交回复
热议问题