I am trying to keep HTTP connection open from my client to my web server, and send every 2 second GET request, I tried the following code, and I see on my web server (using netstat -na |grep 8000) that I have ~30 open connections (concurrent) which are closing and opening.
so my code is not keeping the connection open.
Here is my code:
def GetRestFromGW_Thread(self, gw_ip, runningDir):
URL = "http://" + gw_ip + ":8000/Status.c"
Error = 0
session = requests.Session()
headers = {'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*',
'User-Agent': 'python-requests/2.13.0'}
response = session.get(URL, headers=headers, timeout=5)
while True:
# print("Sending HTTP GET")
try:
response.raise_for_status()
# print(response)
if response.status_code == 200:
# print(response.json())
# print("WRITING TO LOCAL FILE")
try:
with open(runningDir + "/GwRest.json", 'w') as outfile:
json.dump(response.json(), outfile)
outfile.close()
Error = 0
except Exception as e:
print("ERRROR:" + str(e))
pass
except requests.exceptions.HTTPError as errh:
print("HTTPError: " + str(errh))
except requests.exceptions.ConnectionError as errc:
print("Got ConnectionError number: " + str(Error))
Error = Error + 1
except requests.exceptions.Timeout as errt:
print("Timeout: " + str(errt))
except requests.exceptions.RequestException as err:
print("RequestException: " + str(err))
time.sleep(2)
if Error >= 30:
break
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…