socket connect loop - pytohn

Konstantin Krolikov
Konstantin Krolikov used Ask the Experts™
on
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)
s.settimeout(10)
connected = False
    while connected != True:
        try:
            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..
Comment
Watch Question

Do more with

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

Commented:
don't do it yourself, use select http://docs.python.org/library/select.html

recvSockHost = '224.110.0.1'
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, _, _ = select.select([recvSock], [], [], .01)
                  
    for activeSocket in inputReady:
        if activeSocket == recvSock:
           DoStuff()

Open in new window

Author

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

Commented:
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.

Author

Commented:
hhh :)
ok, but this is the right way.
in this way it will keep ask for connection until it enstablish?
Commented:
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.

Cheers,

rico

Author

Commented:
thanks

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