Python Socket 'ConnectionRefusedError: [Errno 61]'

Viewed 52

Im writing a Server-Client program with the socket module. At some point the client connects to the server with 'sock.connect((IP, PORT))' but if there is no server listening for a connection the client throws an exception. My question is how do I catch this exception to try again? Maybe with a 5 second pause in between until the server is up to catch the connection. I have tried:

while True:
   try:
      sock.connect((IP, PORT))
   except ConnectionRefusedError:
      time.sleep(5)

but another exception is thrown 'OSError: [Errno 22] Invalid argument'. Should I catch this exception as well? Is it even possible to catch this exception without ending the program?

1 Answers

I figured it out. The problem was that I tried to use the same socket object to connect again if it has failed. The solution was to just create a new socket with 'sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)'. I don't know if I will get in trouble if I create so many new sockets but it works so far. This code will try to connect 6 times. Code:

timeouts = 5
for i in range(0, timeouts):
   try:
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      sock.connect((IP, PORT))
      break
   except socket.error:
      sock.close()
      print(i)
      if i == timeouts-1:
         exit()
      time.sleep(5)
Related