6262}
6363
6464_default_sock = None # pylint: disable=invalid-name
65- _fake_context = None # pylint: disable=invalid-name
65+ _fake_context = None # pylint: disable=invalid-name
66+
6667
6768class MMQTTException (Exception ):
6869 """MiniMQTT Exception class."""
@@ -85,6 +86,7 @@ def set_socket(sock, iface=None):
8586 _default_sock .set_interface (iface )
8687 _fake_context = _FakeSSLContext (iface )
8788
89+
8890class _FakeSSLSocket :
8991 def __init__ (self , socket , tls_mode ):
9092 self ._socket = socket
@@ -101,6 +103,7 @@ def connect(self, address):
101103 except RuntimeError as error :
102104 raise OSError (errno .ENOMEM ) from error
103105
106+
104107class _FakeSSLContext :
105108 def __init__ (self , iface ):
106109 self ._iface = iface
@@ -200,12 +203,16 @@ def __init__(
200203 self .on_subscribe = None
201204 self .on_unsubscribe = None
202205
203-
204- # pylint: disable=too-many-branches
205206 def _get_socket (self , host , port , * , timeout = 1 ):
207+ """Obtains and connects a new socket to a host.
208+ :param str host: Desired broker hostname
209+ :param int port: Desired broker port
210+ :param int timeout: Desired socket timeout
211+ """
206212 # For reconnections - check if we're using a socket already and close it
207213 if self ._sock :
208214 self ._sock .close ()
215+ self ._sock = None
209216
210217 # Legacy API - use a default socket instead of socket pool
211218 if self ._socket_pool is None :
@@ -224,27 +231,21 @@ def _get_socket(self, host, port, *, timeout=1):
224231 host , port , 0 , self ._socket_pool .SOCK_STREAM
225232 )[0 ]
226233
227- retry_count = 0
228234 sock = None
235+ sock = self ._socket_pool .socket (addr_info [0 ], addr_info [1 ], addr_info [2 ])
229236
230- sock = self ._socket_pool .socket (
231- addr_info [0 ], addr_info [1 ], addr_info [2 ]
232- )
233-
234- connect_host = addr_info [- 1 ][0 ]
235237 if port == 8883 :
236238 sock = self ._ssl_context .wrap_socket (sock , server_hostname = host )
237- connect_host = host
238- sock .settimeout (timeout )
239239
240+ sock .settimeout (timeout )
240241 try :
241- sock .connect ((connect_host , port ))
242+ sock .connect ((addr_info [ - 1 ][ 0 ] , port ))
242243 except MemoryError as err :
243244 sock .close ()
244- raise MemoryError ( err )
245+ raise MemoryError from err
245246 except OSError as err :
246247 sock .close ()
247- raise OSError ( err )
248+ raise OSError from err
248249
249250 self ._backwards_compatible_sock = not hasattr (sock , "recv_into" )
250251 return sock
@@ -409,7 +410,7 @@ def connect(self, clean_session=True, host=None, port=None, keep_alive=None):
409410 if self .logger :
410411 self .logger .debug ("Attempting to establish MQTT connection..." )
411412
412- # Attempt to get a new socket
413+ # Get a new socket
413414 self ._sock = self ._get_socket (self .broker , self .port )
414415
415416 # Fixed Header
0 commit comments