Danii-Sh
Danii-Sh

Reputation: 455

socket programming with python on linux - s.connect() time-out

I'm using a TCP socket to connect to a certain web page, as it will be running in a loop trying to create socket, connect, send data, and receive then close the socket. the problem is s.connect() times out at random iterations and specific web site. i read about TCP time_wait so

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

was added with no luck. then one second of sleep after each iteration, but still no luck. i should note that it works fine in another slower network, but not in the fast one i'm trying to run the code. i think following pseudo code can clarify it more:

while(1)
{time.sleep(1)
s = socket.socket() #TCP socket creation
s.settimeout(2) # 2 seconds for time-out which is more than needed
s.connect()
s.send(message) #which is a HTTP get request
s.recv() # which is a HTTP response
s.close()}

my code routine follows these steps, each of socket methods are implemented correctly, but i get time-outs on connect. i am sure about server functioning correctly. i suspected it might have something to do with TCP time_wait , but comments don't seem to agree

Upvotes: 0

Views: 105

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123531

A connect times out if the TCP handshake with the server is not finished within a specific time, usually because the server does not respond in time. There might be various reasons for is, like the server being down, getting the wrong IP address for the server during DNS lookup, server being overloaded etc.

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Adding this on the client side on the connection has no use.

Adding this on the server side will help if the problem was caused by a crashed server since it will allow the server to bind to the listener address again without waiting and thus the server is faster available again. But, I have no idea if this is really the problem you are facing.

Upvotes: 1

Related Questions