I'm trying to connect to a server on local_host that does nothing more than accept and close the connection. On the client initiation of the connection, I'd like to connect to server with timeout.
Problem: By default, the connection timeout is 1 second, I'd like the connection timeout to be 0.001 seconds. If a connection can not be made within 0.001 seconds with the server(or server script not running) then timeout.
When I try to use settimeout(.001), I obtain unstable results while the server script is running. Sometimes the client script completes fast (as expected), other times the client script hangs (unexpected, since server is script is running). Oddly enough, if you run the client script on it's own (server NOT running) the script behaves stable.
When you remove settimeout(), the problem of unstable goes away all together (with active server script), but this also causes the connection timeout to default to 1 second (unwanted)
server.py
import socket
DEFAULT_CONFIG = {
'address' : 'localhost',
'port' : 8094,
'buffer' : 1023, # Read length
'max_connections' : 700, # Max Number of concurrent connections
}
# start nonblocking server
s_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_socket.setblocking(0)
s_socket.bind( (DEFAULT_CONFIG['address'] , DEFAULT_CONFIG['port']), )
s_socket.listen(DEFAULT_CONFIG['max_connections'] )
print ('server is now listening...')
# Outer Main Loop
while(1):
# normally other stuff can happen here
# We're just going to assume as fast as possible
# Inner loop -> grab as many connections as possible (in one go), and do nothing with them
while(1):
# accept and forget connection (allow client to close it)
try:
conn, addr = s_socket.accept()
conn.close()
except:
break
client.py (to replicate problem, run this multiple times, with and without settimeout(.001))
import socket, time
DEFAULT_CONFIG = {
'address' : 'localhost',
'port' : 8094,
'buffer' : 1023, # Read length
}
# timer to keep track of how long this takes
time_start = time.time()
# open and close 100 connections WITH timeout
for i in range(100):
try:
c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#c_socket.settimeout(.001)
c_socket.connect( (DEFAULT_CONFIG['address'], DEFAULT_CONFIG['port']) )
c_socket.setblocking(0)
c_socket.close()
except:
pass
# how long it took to complete task
print(time.time()- time_start)