0

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

Community
  • 1
  • 1
adama
  • 537
  • 2
  • 10
  • 29
  • Does it abort? If the `backup_server` connection is successful, then the print statement will fire, otherwise you will see an unhandled `ConnectionError` – C.Nivs Sep 10 '19 at 12:42
  • @C.Nivs see my edit – adama Sep 10 '19 at 13:05
  • If `xmpp` will connect to the server, do you need the socket connection? Seems like you are opening two socket handles to the same address. I'm not too familiar with `xmpp` so I'm reading through the documentation at the moment – C.Nivs Sep 10 '19 at 13:47
  • if I remove the ```s.connect()``` I get the ConnectionRefusedError, but the script don´t jumps into the except block – adama Sep 10 '19 at 13:58

0 Answers0