62
62
}
63
63
64
64
_default_sock = None # pylint: disable=invalid-name
65
- _fake_context = None # pylint: disable=invalid-name
65
+ _fake_context = None # pylint: disable=invalid-name
66
+
66
67
67
68
class MMQTTException (Exception ):
68
69
"""MiniMQTT Exception class."""
@@ -85,6 +86,7 @@ def set_socket(sock, iface=None):
85
86
_default_sock .set_interface (iface )
86
87
_fake_context = _FakeSSLContext (iface )
87
88
89
+
88
90
class _FakeSSLSocket :
89
91
def __init__ (self , socket , tls_mode ):
90
92
self ._socket = socket
@@ -101,6 +103,7 @@ def connect(self, address):
101
103
except RuntimeError as error :
102
104
raise OSError (errno .ENOMEM ) from error
103
105
106
+
104
107
class _FakeSSLContext :
105
108
def __init__ (self , iface ):
106
109
self ._iface = iface
@@ -200,12 +203,16 @@ def __init__(
200
203
self .on_subscribe = None
201
204
self .on_unsubscribe = None
202
205
203
-
204
- # pylint: disable=too-many-branches
205
206
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
+ """
206
212
# For reconnections - check if we're using a socket already and close it
207
213
if self ._sock :
208
214
self ._sock .close ()
215
+ self ._sock = None
209
216
210
217
# Legacy API - use a default socket instead of socket pool
211
218
if self ._socket_pool is None :
@@ -224,27 +231,21 @@ def _get_socket(self, host, port, *, timeout=1):
224
231
host , port , 0 , self ._socket_pool .SOCK_STREAM
225
232
)[0 ]
226
233
227
- retry_count = 0
228
234
sock = None
235
+ sock = self ._socket_pool .socket (addr_info [0 ], addr_info [1 ], addr_info [2 ])
229
236
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 ]
235
237
if port == 8883 :
236
238
sock = self ._ssl_context .wrap_socket (sock , server_hostname = host )
237
- connect_host = host
238
- sock .settimeout (timeout )
239
239
240
+ sock .settimeout (timeout )
240
241
try :
241
- sock .connect ((connect_host , port ))
242
+ sock .connect ((addr_info [ - 1 ][ 0 ] , port ))
242
243
except MemoryError as err :
243
244
sock .close ()
244
- raise MemoryError ( err )
245
+ raise MemoryError from err
245
246
except OSError as err :
246
247
sock .close ()
247
- raise OSError ( err )
248
+ raise OSError from err
248
249
249
250
self ._backwards_compatible_sock = not hasattr (sock , "recv_into" )
250
251
return sock
@@ -409,7 +410,7 @@ def connect(self, clean_session=True, host=None, port=None, keep_alive=None):
409
410
if self .logger :
410
411
self .logger .debug ("Attempting to establish MQTT connection..." )
411
412
412
- # Attempt to get a new socket
413
+ # Get a new socket
413
414
self ._sock = self ._get_socket (self .broker , self .port )
414
415
415
416
# Fixed Header
0 commit comments