Search code examples
pythonsocketsnetwork-programmingtcptcpclient

Python - How to check if socket is still connected


I have the following code, which is self explanatory:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(host, port)
s.send("some data")
# don't close socket just yet... 
# do some other stuff with the data (normal string operations)
if s.stillconnected() is true:
    s.send("some more data")
if s.stillconnected() is false:
    # recreate the socket and reconnect
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(host, port)
    s.send("some more data")
s.close()

How do I implement s.stillconnected() I do not wish to recreate the socket blindly.


Solution

  • If the server connection is no longer alive, calling the send method will throw an exception, so you can use a try-exception block to attempt to send data, catch the exception if it's thrown, and reestablish the connection:

    try:
        s.send("some more data")
    except:
        # recreate the socket and reconnect
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(host, port)
        s.send("some more data")
    

    EDIT: As per @Jean-Paul Calderone's comments, please consider using the sendall method, which is a higher level method that sends all the data or throws an error, instead of send, which is a lower level method that does not guarantee the transmission of all the data, OR use higher level modules like an HTTP library that can handle socket lifecycles.