Reconnect a Python socket after it has lost its connection

Reconnect a Python socket after it has lost its connection

Learn how to automatically attempt to reconnect a Python client socket once it has lost its connection to the server socket


When creating a network using sockets, sometimes it can be necessary to implement an automatic re-connection system for when a client socket loses its connection to the server socket. This could be a necessity to the application, or just for the user's convenience.


In Python, when a socket loses its connection to the host, the socket will be closed by the operating system, this will result in errors if you try to read or write to the socket stream, this at least gives you a way to detect the loss of connection. All you will need to do afterwards is create a new socket and attempt to reconnect to the host.


The below examples are compatible with Python version 3 and up.


Detecting a loss of connection to the server


When a loss of connectivity occurs between the client and server socket, the operating system closes the socket that was holding the connection open, so if you attempt to read or write to the socket stream, it will result in an exception.


To detect a loss of connection, all you need to do is surround any socket read or write operations in a try-except statement that listens for a socket exception.


try:  
    clientSocket.send( bytes( "test", "UTF-8" ) )  
except socket.error:  
    # reconnect to the server here  


If this exception is caught, you will know that you most likely need to reconnect to the server.


Reconnecting to the server once loss of connection is detected


As the socket object is no longer useful after the connection is lost, it is necessary to create a new socket object (this can be assigned to the initial socket variable).


Once you have recreated the client socket, you can then try to reconnect to the server using the connect() method. The problem with this is that the issue that caused the loss of connection may still be affecting the system, this means the connect() method could result in an exception such as a "ConnectionRefusedError" (caused by the server not actively listening for connections).


A simple solution to this issue is to place the connect() method within a while loop and surround it with a try-except statement. If the connection is successful, then the application will continue with the rest of the script, otherwise it will wait a few seconds and attempt to reconnect again.


print( "connection lost... reconnecting" )  
connected = False  
  
# recreate socket  
clientSocket = socket.socket()  
  
while not connected:  
    # attempt to reconnect, otherwise sleep for 2 seconds  
    try:  
        clientSocket.connect( ( host, port ) )  
        connected = True  
        print( "re-connection successful" )  
    except socket.error:  
        sleep( 2 )  
  
# continue normal operations  

The above script will keep the application within the while loop until it has successfully reconnected to the server socket.


Full example


Here we will create a simple local server and client that will both send and receive simple messages from each-other for as long as they are connected. If the client loses connection to the server, it will try to reconnect.


server.py

import socket  
from time import sleep  
  
# create and configure socket on local host  
serverSocket = socket.socket()  
host = socket.gethostname()  
port = 25000 #arbitrary port  
serverSocket.bind( ( host, port ) )  
serverSocket.listen( 1 )  
  
con, addr = serverSocket.accept()  
  
print( "connected to client" )  
  
while True:  
    # send wave to client  
    con.send( bytes( "Server wave", "UTF-8" ) )  
  
    # receive wave from client  
    message = con.recv( 1024 ).decode( "UTF-8" )  
    print( message )  
  
    # wait 1 second  
    sleep( 1 )  
  
con.close();  


client.py

import socket  
from time import sleep  
  
# configure socket and connect to server  
clientSocket = socket.socket()  
host = socket.gethostname()  
port = 25000  
clientSocket.connect( ( host, port ) )  
  
# keep track of connection status  
connected = True  
print( "connected to server" )  
  
while True:  
    # attempt to send and receive wave, otherwise reconnect  
    try:  
        message = clientSocket.recv( 1024 ).decode( "UTF-8" )  
        clientSocket.send( bytes( "Client wave", "UTF-8" ) )  
        print( message )  
    except socket.error:  
        # set connection status and recreate socket  
        connected = False  
        clientSocket = socket.socket()  
        print( "connection lost... reconnecting" )  
        while not connected:  
            # attempt to reconnect, otherwise sleep for 2 seconds  
            try:  
                clientSocket.connect( ( host, port ) )  
                connected = True  
                print( "re-connection successful" )  
            except socket.error:  
                sleep( 2 )  
  
clientSocket.close();  


If you have any questions or anything to add feel free to leave a comment below!



Christopher Thornton@Instructobit 6 years ago
or