adafruit / Adafruit_CircuitPython_Wiznet5k

Pure-Python interface for WIZNET 5k Ethernet modules
Other
15 stars 37 forks source link

recv hangs if there’s no timeout and connection closes #135

Closed JetForMe closed 6 months ago

JetForMe commented 10 months ago

recv() is supposed to return a 0-length bytes object when the connection closes. But the check for bytes, although it tests the timeout, doesn’t test the connection status, and thus hangs forever if the connection closes.

JetForMe commented 10 months ago

This is a potential fix:

        while not self._available():
            if self._status in (wiznet5k.adafruit_wiznet5k.SNSR_SOCK_CLOSED, wiznet5k.adafruit_wiznet5k.SNSR_SOCK_CLOSE_WAIT):
                break
    @_check_socket_closed
    def recv(
        # pylint: disable=too-many-branches
        self,
        bufsize: int,
        flags: int = 0,
    ) -> bytes:
        """
        Receive data from the socket. The return value is a bytes object representing the data
        received. The maximum amount of data to be received at once is specified by bufsize.

        :param int bufsize: Maximum number of bytes to receive.
        :param int flags: ignored, present for compatibility.

        :return bytes: Data from the socket.
        """
        stamp = time.monotonic()
        while not self._available():
            if self._status in (wiznet5k.adafruit_wiznet5k.SNSR_SOCK_CLOSED, wiznet5k.adafruit_wiznet5k.SNSR_SOCK_CLOSE_WAIT):
                break
            if self._timeout and 0 < self._timeout < time.monotonic() - stamp:
                break
            time.sleep(0.05)
        bytes_on_socket = self._available()
        if not bytes_on_socket:
            return b""
        bytes_to_read = min(bytes_on_socket, bufsize)
        if self._sock_type == SOCK_STREAM:
            bytes_read = _the_interface.socket_read(self._socknum, bytes_to_read)[1]
        else:
            bytes_read = _the_interface.read_udp(self._socknum, bytes_to_read)[1]
        gc.collect()
        return bytes(bytes_read)