How to implement guide with socket timeout handling in non-blocking mode with python 3.10
I keep running into I'm trying to implement Hey everyone, I'm running into an issue that's driving me crazy. I tried several approaches but none seem to work. I'm working on a TCP client using Python 3.10 with the `socket` library, and I'm working with an scenario where my socket does not timeout as expected when in non-blocking mode. I've set the socket to non-blocking using `socket.setblocking(0)`, but I still receive the data indefinitely without any timeout. I intended to limit the waiting time while receiving data to 5 seconds. I've implemented a retry loop like this: ```python import socket import time HOST = '127.0.0.1' PORT = 65432 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.setblocking(0) # Set non-blocking mode s.connect((HOST, PORT)) data = None start_time = time.time() while data is None: try: data = s.recv(1024) except BlockingIOError: if time.time() - start_time > 5: print('Timeout exceeded') break continue if data: print('Received', data) else: print('No data received') ``` I expect to see 'Timeout exceeded' printed if no data is received within 5 seconds, but instead, it keeps looping indefinitely when there's no data to read. I'm not sure if I'm missing something with the non-blocking socket or the way I'm handling the timeout. Any insights into how to properly implement a timeout in non-blocking mode would be greatly appreciated! For context: I'm using Python on macOS. My development environment is Windows. What's the best practice here? Am I approaching this the right way? I'm coming from a different tech stack and learning Python. Any help would be greatly appreciated! This is happening in both development and production on CentOS.