Skip to content Skip to sidebar Skip to footer

No Connection. Please Reconnect and Try Opening the Spreadsheet Again.

Reconnect a Python socket after it has lost its connection

Reconnect a Python socket after information technology has lost its connection

Larn how to automatically attempt to reconnect a Python client socket one time 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 connectedness to the host, the socket will be closed by the operating organisation, this volition result in errors if you try to read or write to the socket stream, this at least gives you lot a way to notice the loss of connection. All you will demand to do later is create a new socket and attempt to reconnect to the host.

The beneath examples are compatible with Python version three and upwardly.

Detecting a loss of connection to the server

When a loss of connectivity occurs between the customer 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 effect in an exception.

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

              try:       clientSocket.ship( bytes(              "test",              "UTF-8"              ) )              except              socket.error:                   

If this exception is caught, you will know that y'all most probable demand to reconnect to the server.

Reconnecting to the server one time 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 tin can exist assigned to the initial socket variable).

Once you accept recreated the client socket, you tin so endeavor 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 issue in an exception such as a "ConnectionRefusedError" (caused by the server non actively listening for connections).

A unproblematic solution to this issue is to identify the connect() method within a while loop and surround it with a try-except statement. If the connectedness is successful, then the application will keep with the rest of the script, otherwise it will await a few seconds and attempt to reconnect over again.

print(              "connection lost... reconnecting"              )   continued =              False               clientSocket = socket.socket()              while              not              connected:                     attempt:           clientSocket.connect( ( host, port ) )           connected =              True              print(              "re-connectedness successful"              )              except              socket.error:           slumber(              ii              )                  

The to a higher place script volition keep the application within the while loop until it has successfully reconnected to the server socket.

Full example

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

server.py

import              socket              from              fourth dimension              import              sleep               serverSocket = socket.socket()   host = socket.gethostname()   port =              25000               serverSocket.bind( ( host, port ) )   serverSocket.listen(              1              )      con, addr = serverSocket.accept()              print(              "connected to client"              )              while              True:            con.send( bytes(              "Server moving ridge",              "UTF-8"              ) )               message = con.recv(              1024              ).decode(              "UTF-viii"              )              impress( message )                        sleep(              i              )      con.close();            

customer.py

              import              socket              from              time              import              slumber       clientSocket = socket.socket()   host = socket.gethostname()   port =              25000              clientSocket.connect( ( host, port ) )       connected =              True              print(              "connected to server"              )              while              True:                     effort:           bulletin = clientSocket.recv(              1024              ).decode(              "UTF-8"              )           clientSocket.transport( bytes(              "Client wave",              "UTF-eight"              ) )           print( message )              except              socket.error:                    connected =              Fake              clientSocket = socket.socket()           print(              "connectedness lost... reconnecting"              )              while              not              continued:                             try:                   clientSocket.connect( ( host, port ) )                   connected =              True              print(              "re-connection successful"              )              except              socket.error:                   slumber(              two              )      clientSocket.close();            

If you take whatever questions or annihilation to add experience complimentary to leave a comment beneath!


person Writer: Instructobit
access_time Modified: 1 twelvemonth ago
bar_chart Views: 35783
more Tags: networks python

Auto saves

Looking for connections in the globe of IT? Bring together our community and notice other helpful and friendly developers, admins, engineers, and other It people here!

close

Recommended

Run into something you don't agree with or experience could be improved?


Not finding what you lot were looking for or accept an idea for a tutorial?

close

buntinlattens.blogspot.com

Source: https://instructobit.com/tutorial/101/Reconnect-a-Python-socket-after-it-has-lost-its-connection

Enregistrer un commentaire for "No Connection. Please Reconnect and Try Opening the Spreadsheet Again."