3030"""
3131
3232
33-
33+ import time
3434from micropython import const
3535
3636_the_interface = None # pylint: disable=invalid-name
@@ -63,6 +63,7 @@ def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
6363 raise RuntimeError ("Only SOCK_STREAM type supported" )
6464 self ._buffer = b''
6565 self ._socknum = _the_interface .get_socket ()
66+ self .settimeout (0 )
6667
6768 def connect (self , address , conntype = None ):
6869 """Connect the socket to the 'address' (which can be 32bit packed IP or
@@ -81,7 +82,7 @@ def readline(self):
8182 """Attempt to return as many bytes as we can up to but not including '\r \n '"""
8283 while b'\r \n ' not in self ._buffer :
8384 # there's no line already in there, read some more
84- avail = _the_interface .socket_available (self ._socknum )
85+ avail = min ( _the_interface .socket_available (self ._socknum ), 4000 )
8586 if avail :
8687 self ._buffer += _the_interface .socket_read (self ._socknum , avail )
8788 firstline , self ._buffer = self ._buffer .split (b'\r \n ' , 1 )
@@ -90,21 +91,28 @@ def readline(self):
9091 def read (self , size = 0 ):
9192 """Read up to 'size' bytes from the socket, this may be buffered internally!
9293 If 'size' isnt specified, return everything in the buffer."""
93- avail = _the_interface .socket_available (self ._socknum )
94- if avail :
95- self ._buffer += _the_interface .socket_read (self ._socknum , avail )
9694 if size == 0 : # read as much as we can at the moment
95+ avail = min (_the_interface .socket_available (self ._socknum ), 4000 )
96+ if avail :
97+ self ._buffer += _the_interface .socket_read (self ._socknum , avail )
9798 ret = self ._buffer
9899 self ._buffer = b''
99100 return ret
101+ stamp = time .monotonic ()
100102 while len (self ._buffer ) < size :
101- avail = _the_interface .socket_available (self ._socknum )
103+ avail = min ( _the_interface .socket_available (self ._socknum ), 4000 )
102104 if avail :
103- self ._buffer += _the_interface .socket_read (self ._socknum , avail )
105+ stamp = time .monotonic ()
106+ self ._buffer += _the_interface .socket_read (self ._socknum , min (size , avail ))
107+ if time .monotonic () - stamp > self ._timeout :
108+ break
104109 ret = self ._buffer [:size ]
105110 self ._buffer = self ._buffer [size :]
106111 return ret
107112
113+ def settimeout (self , value ):
114+ self ._timeout = value
115+
108116 def close (self ):
109117 """Close the socket, after reading whatever remains"""
110118 _the_interface .socket_close (self ._socknum )
0 commit comments