I am using sleekxmpp to send python responses to an instant messenger. I have an active and a backup server.
Currently I am connection to the active server like described in the docs.
if xmpp.connect(('myserver', myport)):
xmpp.process(block=True)
print("Done")
else:
print("Unable to connect.")
Lately I received a [WinError 10061] ConnectionRefusedError
. I don´t want to manually change the server to the backup-server, so I try to implement a try-except
block.
This is what I got so far
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(('myserver', myport))
except:
print("not able to connect to myserver")
After executing the script I get the error message with the print. So far so good. But now I want to implement a second connect if the first connection to the main-server fails.
I am pretty new to exceptions and sockets in python, I don´t know how to achieve this. I tried the block below but the script automatically aborts with the print from the try block.
try:
s.connect(('active_server', myport))
except:
s.connect(('backup_server', myport))
print("not able to connect to both servers")
Could you give some assistance?
EDIT: I have a working solution now, but this seems to be very bad coding.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(('active_server', myport))
xmpp.connect(('active_server', myport))
except:
print("Can´t connect to active_server, try to connect to backup_server...")
xmpp.connect(('backup_server', myport))
xmpp.process(block=True)
First xmpp.process
is necessary. Second s.connect()
I think just connects to the socket, but xmpp.connect()
is necessary to connect the python script to the IM server.
In other words: I check if I can connect to active_server:myport
generally, if yes, I connect via xmpp.connect()
. But there must be a much better solution than mine