socket connect loop - pytohn

Konstantin Krolikov
Konstantin Krolikov used Ask the Experts™
hello experts,
i created a simple chat server using socket in python.

my problem is that i want the client to try connect to the server until the connection is made..(when i set the timeout of the socket)

however, when the connection fail(timeout), i did another request but it done immediately.
here is the code:
from socket import *
s = socket(AF_INET, SOCK_STREAM)
connected = False
    while connected != True:
            s.connect(('localhost', 12345))
            connected = True
        except error:
            print "could not connected to server now.. Tries to connect again.."

#rest of the code...

Open in new window

is there any way to reset the timeout or i have to close that socket and open new one..

by the way, only when i set the timeout of the socket it doesn't work, if i don't set the timeout of the socket, it works..

thanks ahead..
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

don't do it yourself, use select

recvSockHost = ''
recvSockPort = 10001

recvSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
recvSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
recvSockId = recvSock.fileno()

inputReady, _, _ =[recvSock], [], [], .01)
    for activeSocket in inputReady:
        if activeSocket == recvSock:

Open in new window


but how can i do it myself?
i want to know this..

Understandable, but when the wheel has been invented several times (with much better results)  why do you want to make a square wheel?
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.


hhh :)
ok, but this is the right way.
in this way it will keep ask for connection until it enstablish?
If you REALY want to do this.  After you get connection == True, just reset the timeout.
s.timeout(0).  Then what you are try'n to do will work.  Anywhere in the code after assignment you can change the timeout.





Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial