Python: Close TCP client connection to server after no server message for x seconds
I'm trying to create Python TCP client. It is fully functional, but I desire a functionality where if a "connected" message hasn't been recieved from the server for x seconds, then I can close my connection. I currently have a separate thread for recieving messages from the server. Basically, if I receive a message that says "connected" I want to reset a timer.
I've tried a few different approaches to solving it. I've tried to have a separate thread with a timer that keep track of when to disconnect using global variables which is a messy solution which didn't work regardless. I tried to make my own threading subclass but I still was not able to solve the problem and it introduced a lot more complexity than I really need.
a simple approach that I took was to try to have a timer in the while loop in my recieve function. This works for disconnecting from the server, but it will only timeout when a message is sent (due to the try block) and not actually the second the timer is up.
import threading, time, sys def main(): host = sys.argv port = sys.argv sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) address = (host, port) sock.connect(address) rec_thread = threading.Thread(target=rec, args=(sock,)) rec_thread.setDaemon(True) rec_thread.start() while True: message = input() sock.sendall(str.encode(message)) def rec(sock): start_time = time.time() while True: elapsed_time = time.time() - start_time if(elapsed_time > 10): sock.close() try: msg = sock.recv(1024).decode("utf8") if msg == 'connected': start_time = time.time() else: print(msg) except KeyboardInterrupt: sock.close() break
If I use this approach then I will only actually close the connection after I recieve a message from the server.
ex: I want it to disconnect immediately after 10s, but if I don't get any message from the server until 14s, then it won't disconnect until 14s.