F.N F.N - 12 days ago 8
Python Question

Prevent application from closing due to a 'connection refused' error

I am writing a Python client which connects with simple sockets in a server (also written in Python). I want to prevent client termination when the connection in server refused. In other words, I want to make client "search" for the server (if there is no connection) every 30 seconds.

Here is the code I wrote, but when the connection terminates from the server, the client returns an error for connection refused, and terminates itself.

Code:

#!/usr/bin/python

import socket
import time

while True:

sock = socket.socket()
host = socket.gethostname()
port = 4444
conn = sock.connect((host,port))

while(conn != None):
print 'Waiting for the server'
time.sleep(30)
sock = socket.socket()
host = socket.gethostname()
port = 4444
conn = sock.connect((host,port))

while True:

recv_buf = sock.recv(1024)

if (recv_buf == 'exit'):
break

print(recv_buf)
sock.send('hi server')


Error:


Traceback (most recent call last): File "s_client.py", line 12, in



conn = sock.connect((host,port)) File "C:\Program Files\python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args) socket.error: [Errno 10061] ─ίΊ ▐ΪάΊ ϊΫΊάΪ▐ ύ ϊύΉώΎΫ±ή▀ά ≤²Ίϊί≤ύ≥,


So any idea, that will help not to terminate the client, but to make it continuously look for the server, is welcome.

rjv rjv
Answer

Use try-except:

conn = None
while(conn == None):
    sock = socket.socket()
    host = socket.gethostname()
    port = 4444
    try:
        conn = sock.connect((host,port))
    except:
         print 'Waiting for the server'
         time.sleep(30)

It's better to avoid the initial connect call and perform the connect only through the connect in the while loop. I have made a few other changes too, like moving the sleep call to the except part.

Comments