Skip to content

Unclear behaviour of recv(timeout=0) for Server (threading)Β #1552

@savejeff

Description

@savejeff

I think the behavior of recv(timeout=0) for the Thread-based Server is unclear.
Due to the design of my application, I can't use the "for message in websocket" and have to resort to an update() function that I call frequently to check if messages were received:


def update(self) -> None:
	"""
	Check for received data with proper handling of timeouts and connection closure.
	"""
	while True:
		try:
			# Attempt to receive data with a timeout
			data_rx = self.ws_client.recv(timeout=0)
		except TimeoutError:
			# No data received within the timeout period
			break
		except websockets.exceptions.ConnectionClosed as e:
			# Handle connection closure
			Log(f"Connection closed: {e}")
			self._is_connected = False
			break
		except Exception as e:
			# Handle any other exceptions
			Log(f"Error occurred: {e}")
			self._is_connected = False
			break

		# If no data received, exit the loop
		if data_rx is None:
			break

		self.log(f"RX: {data_rx}")


I was expecting when I set timeout=0 that only when a message was received I get it otherwise TimeoutError is raised so it's not blocking.
the behavior I'm getting is that with very low values like timeout=0.001 (1ms) it works, but with 0 I don't receive any messages.

Have I understood timeout=0 incorrectly? In the documentation it says:
"Set timeout to 0 to check if a message was already received." see

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions